[go: up one dir, main page]

0% found this document useful (0 votes)
3 views18 pages

Week 11

The document provides an overview of file handling and exception management in Java, detailing the use of `FileReader` and `FileWriter` for file operations and the importance of handling exceptions using `try-catch`, `finally`, `throw`, and `throws`. It classifies exceptions into checked and unchecked categories, explaining their characteristics and common causes. Proper exception handling is emphasized as essential for robust Java programming.

Uploaded by

Pankaja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Week 11

The document provides an overview of file handling and exception management in Java, detailing the use of `FileReader` and `FileWriter` for file operations and the importance of handling exceptions using `try-catch`, `finally`, `throw`, and `throws`. It classifies exceptions into checked and unchecked categories, explaining their characteristics and common causes. Proper exception handling is emphasized as essential for robust Java programming.

Uploaded by

Pankaja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

## **Java Files and Exception Handling Notes**

### **1. Files and I/O Streams in Java**

In Java, file handling is performed using classes from the `java.io` package. These classes allow reading
and writing data from files.

#### **1.1 File Reader and Writer**

- **`FileReader`** and **`FileWriter`** are used for reading and writing character data in Java.

##### **FileReader**

- Used to read data from a file.

- Reads character by character.

- Requires handling `IOException`.

**Example: Reading from a file using `FileReader`**

```java

import java.io.FileReader;

import java.io.IOException;

public class FileReaderExample {

public static void main(String[] args) {

try (FileReader fr = new FileReader("input.txt")) {

int ch;

while ((ch = fr.read()) != -1) {

System.out.print((char) ch);

}
} catch (IOException e) {

System.out.println("Error reading file: " + e.getMessage());

```

##### **FileWriter**

- Used to write data into a file.

- Writes character by character.

- Requires handling `IOException`.

**Example: Writing to a file using `FileWriter`**

```java

import java.io.FileWriter;

import java.io.IOException;

public class FileWriterExample {

public static void main(String[] args) {

try (FileWriter fw = new FileWriter("output.txt")) {

fw.write("Hello, Java File Handling!");

System.out.println("Data written successfully.");

} catch (IOException e) {

System.out.println("Error writing file: " + e.getMessage());

}
}

```

---

### **2. Exception Concept**

An **exception** is an event that disrupts the normal flow of a program. It occurs during runtime due
to various reasons like invalid input, file not found, or division by zero.

#### **2.1 Exceptions in Java**

Java provides a robust exception-handling mechanism that allows developers to handle errors
gracefully.

**Common causes of exceptions:**

- Division by zero (`ArithmeticException`)

- Null reference (`NullPointerException`)

- Invalid file access (`IOException`)

- Array index out of bounds (`ArrayIndexOutOfBoundsException`)

#### **2.2 Classification of Exceptions**

Java exceptions are categorized into two types:

1. **Checked Exceptions** (Compile-time exceptions)

- Must be handled using `try-catch` or declared using `throws`.

- Examples:
- `IOException`

- `SQLException`

- `FileNotFoundException`

2. **Unchecked Exceptions** (Runtime exceptions)

- Occur at runtime due to programming errors.

- Not required to be handled explicitly.

- Examples:

- `NullPointerException`

- `ArithmeticException`

- `ArrayIndexOutOfBoundsException`

---

### **3. Exception Handling in Java**

Java provides a structured way to handle exceptions using `try`, `catch`, `finally`, `throw`, and `throws`
keywords.

#### **3.1 try-catch block**

- The `try` block contains the code that may throw an exception.

- The `catch` block handles the exception.

**Example: Handling division by zero**

```java

public class ExceptionExample {

public static void main(String[] args) {


try {

int result = 10 / 0; // This will cause an exception

System.out.println(result);

} catch (ArithmeticException e) {

System.out.println("Error: Division by zero is not allowed.");

```

#### **3.2 finally block**

- The `finally` block executes whether an exception occurs or not.

- It is mainly used for resource cleanup.

**Example: Using `finally` for resource management**

```java

import java.io.FileReader;

import java.io.IOException;

public class FinallyExample {

public static void main(String[] args) {

FileReader fr = null;

try {

fr = new FileReader("input.txt");

int ch;
while ((ch = fr.read()) != -1) {

System.out.print((char) ch);

} catch (IOException e) {

System.out.println("File not found.");

} finally {

try {

if (fr != null) fr.close();

System.out.println("\nFile closed.");

} catch (IOException e) {

System.out.println("Error closing file.");

```

#### **3.3 throw keyword**

- Used to manually throw an exception.

**Example: Throwing a custom exception**

```java

public class ThrowExample {

public static void checkAge(int age) {

if (age < 18) {


throw new ArithmeticException("Not eligible to vote.");

System.out.println("You are eligible to vote.");

public static void main(String[] args) {

checkAge(16);

```

#### **3.4 throws keyword**

- Used to declare exceptions that a method might throw.

- Allows exception propagation to the calling method.

**Example: Declaring exceptions using `throws`**

```java

import java.io.FileReader;

import java.io.IOException;

public class ThrowsExample {

public static void readFile() throws IOException {

FileReader fr = new FileReader("input.txt");

fr.close();

}
public static void main(String[] args) {

try {

readFile();

} catch (IOException e) {

System.out.println("Handled IOException: " + e.getMessage());

```

---

### **Summary**

1. **File Handling in Java**

- `FileReader` for reading files.

- `FileWriter` for writing to files.

- Requires handling `IOException`.

2. **Exception Handling in Java**

- **Checked Exceptions:** Must be handled (e.g., `IOException`).

- **Unchecked Exceptions:** Occur at runtime (e.g., `NullPointerException`).

- `try-catch`: Catches and handles exceptions.

- `finally`: Ensures resource cleanup.

- `throw`: Manually throws an exception.


- `throws`: Declares exceptions that might be thrown.

These concepts are essential for robust Java programming, ensuring both smooth execution and proper
error handling.

# **Detailed Notes on Java Files and Exception Handling**

Java provides built-in support for file handling and exception management to ensure smooth execution
of programs. Below are the key concepts related to **Files and I/O Streams** and **Exception
Handling** in Java.

---

## **1. Files and I/O Streams in Java**

Java provides the `java.io` package for handling files and input/output (I/O) operations. The two primary
types of streams are:

- **Byte Streams**: Used for handling binary data (e.g., images, audio files). Classes include
`FileInputStream` and `FileOutputStream`.

- **Character Streams**: Used for handling text data. Classes include `FileReader` and `FileWriter`.

### **1.1 FileReader**

- `FileReader` is a character-based input stream that reads data from a file.

- It reads the file character by character.

#### **Example: Reading a file using `FileReader`**


```java

import java.io.FileReader;

import java.io.IOException;

public class FileReaderExample {

public static void main(String[] args) {

try (FileReader fr = new FileReader("input.txt")) {

int ch;

while ((ch = fr.read()) != -1) {

System.out.print((char) ch);

} catch (IOException e) {

System.out.println("Error reading file: " + e.getMessage());

```

### **1.2 FileWriter**

- `FileWriter` is a character-based output stream that writes data to a file.

- It writes data character by character and can overwrite or append data.

#### **Example: Writing to a file using `FileWriter`**

```java

import java.io.FileWriter;

import java.io.IOException;
public class FileWriterExample {

public static void main(String[] args) {

try (FileWriter fw = new FileWriter("output.txt")) {

fw.write("Hello, Java File Handling!");

System.out.println("Data written successfully.");

} catch (IOException e) {

System.out.println("Error writing file: " + e.getMessage());

```

**Key Features:**

- `FileReader` and `FileWriter` are used for handling text files.

- They handle character data, unlike `FileInputStream` and `FileOutputStream`, which handle byte data.

- `try-with-resources` ensures automatic resource management.

---

## **2. Exception Concept in Java**

An **exception** is an event that disrupts the normal execution of a program. In Java, exceptions are
objects that describe an error that occurs during program execution.

### **2.1 Common Causes of Exceptions**

- **Invalid user input** (e.g., dividing by zero).

- **Accessing an array element out of bounds.**


- **File not found while reading a file.**

- **Null reference access.**

- **Database connectivity failures.**

---

## **3. Classification of Exceptions**

Java exceptions are broadly classified into two categories:

### **3.1 Checked Exceptions (Compile-time exceptions)**

- These exceptions must be handled using `try-catch` or declared using `throws`.

- They occur at **compile time** and prevent compilation if not handled.

- Examples:

- `IOException` (e.g., when reading a non-existent file).

- `SQLException` (when database access fails).

- `FileNotFoundException` (when the file is not found).

**Example: Handling `IOException` (Checked Exception)**

```java

import java.io.FileReader;

import java.io.IOException;

public class CheckedExceptionExample {

public static void main(String[] args) {

try {
FileReader fr = new FileReader("nonexistentfile.txt");

} catch (IOException e) {

System.out.println("File not found: " + e.getMessage());

```

### **3.2 Unchecked Exceptions (Runtime exceptions)**

- These exceptions occur at **runtime** due to programming errors.

- They do not require explicit handling (though handling is recommended).

- Examples:

- `NullPointerException`

- `ArithmeticException` (e.g., division by zero)

- `ArrayIndexOutOfBoundsException`

**Example: Unchecked Exception (Division by Zero)**

```java

public class UncheckedExceptionExample {

public static void main(String[] args) {

int a = 10, b = 0;

int result = a / b; // This will cause ArithmeticException

System.out.println(result);

}
```

- This code will throw `ArithmeticException` at runtime.

---

## **4. Exception Handling in Java**

Java provides mechanisms to **handle exceptions gracefully** without crashing the program. Exception
handling is implemented using:

### **4.1 try-catch block**

- The `try` block contains the code that may generate an exception.

- The `catch` block handles the exception and prevents program termination.

#### **Example: Handling Division by Zero**

```java

public class TryCatchExample {

public static void main(String[] args) {

try {

int result = 10 / 0;

System.out.println(result);

} catch (ArithmeticException e) {

System.out.println("Error: Division by zero is not allowed.");

```
---

### **4.2 finally block**

- The `finally` block executes whether an exception occurs or not.

- It is used to release resources such as file handles or database connections.

#### **Example: Using `finally` for File Handling**

```java

import java.io.FileReader;

import java.io.IOException;

public class FinallyExample {

public static void main(String[] args) {

FileReader fr = null;

try {

fr = new FileReader("input.txt");

System.out.println("File opened successfully.");

} catch (IOException e) {

System.out.println("File not found.");

} finally {

try {

if (fr != null) {

fr.close();

System.out.println("File closed.");
}

} catch (IOException e) {

System.out.println("Error closing file.");

```

---

### **4.3 throw Keyword**

- The `throw` keyword is used to **manually throw an exception**.

#### **Example: Throwing a Custom Exception**

```java

public class ThrowExample {

public static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Not eligible to vote.");

System.out.println("You are eligible to vote.");

public static void main(String[] args) {


checkAge(16);

```

- This program throws an `ArithmeticException` if the age is less than 18.

---

### **4.4 throws Keyword**

- The `throws` keyword is used to declare exceptions that a method may throw.

#### **Example: Declaring Exceptions Using `throws`**

```java

import java.io.FileReader;

import java.io.IOException;

public class ThrowsExample {

public static void readFile() throws IOException {

FileReader fr = new FileReader("input.txt");

fr.close();

public static void main(String[] args) {

try {

readFile();
} catch (IOException e) {

System.out.println("Handled IOException: " + e.getMessage());

```

- The method `readFile()` declares that it may throw an `IOException`.

---

## **5. Summary**

| **Concept** | **Description** |

|------------|----------------|

| **FileReader** | Reads data from a file (character-based). |

| **FileWriter** | Writes data to a file (character-based). |

| **Checked Exceptions** | Must be handled (e.g., `IOException`). |

| **Unchecked Exceptions** | Occur at runtime (e.g., `NullPointerException`). |

| **try-catch** | Handles exceptions to prevent crashes. |

| **finally** | Ensures execution of essential cleanup code. |

| **throw** | Manually throws an exception. |

| **throws** | Declares that a method may throw an exception. |

By handling exceptions properly, Java ensures that applications **run smoothly**, even when
unexpected errors occur.

You might also like