Examples of Exception Handling in Java
Q: Can you provide an example of a scenario where you would use exception handling in your Java code?
- Java Exception Handling
- Junior level question
Explore all the latest Java Exception Handling interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java Exception Handling interview for FREE!
Certainly! One common scenario where exception handling is essential in Java is when dealing with file input and output operations. For instance, when attempting to read a file, there are various issues that can arise, such as the file not existing, lacking permission to access the file, or encountering an I/O error while reading.
Here’s an example:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileProcessor {
public static void readFile(String filePath) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("An error occurred while reading the file: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Failed to close the reader: " + e.getMessage());
}
}
}
public static void main(String[] args) {
readFile("example.txt");
}
}
```
In the above code, we use a try-catch block to handle `IOException`, which covers scenarios like the file not being found or issues during reading. The finally block ensures that resources are released properly, even in the event of an exception. This way, we prevent resource leaks and provide meaningful error messages to the user, enhancing the robustness of the application.
Here’s an example:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileProcessor {
public static void readFile(String filePath) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("An error occurred while reading the file: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Failed to close the reader: " + e.getMessage());
}
}
}
public static void main(String[] args) {
readFile("example.txt");
}
}
```
In the above code, we use a try-catch block to handle `IOException`, which covers scenarios like the file not being found or issues during reading. The finally block ensures that resources are released properly, even in the event of an exception. This way, we prevent resource leaks and provide meaningful error messages to the user, enhancing the robustness of the application.


