Module 3
Exception Handling & File I/O in Java
25 mins read
Lesson 1: Exception Handling
1.1 Introduction to Exception Handling
Exception handling in Java provides a mechanism to manage runtime errors using try-catch-finally blocks, ensuring smooth program execution without crashing.
JAVA
// Example of try-catch block
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
1.2 Checked vs Unchecked Exceptions
Checked exceptions are verified at compile-time (e.g. IOException), while unchecked exceptions occur at runtime (e.g. NullPointerException).
JAVA
// Checked exception handling
try {
FileReader file = new FileReader("file.txt");
} catch (IOException e) {
System.out.println("Error: File not found");
}
// Unchecked exception example
String str = null;
System.out.println(str.length()); // Throws NullPointerException