What is Exception Handling in Java?
Exception Handling is a mechanism to handle runtime errors gracefully, preventing abrupt program termination.
1. try-catch Block
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
}
System.out.println("Program continues normally");
}
}
2. finally Block
Executes whether exception occurs or not (cleanup code).
import java.io.*;
public class FinallyExample {
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("test.txt");
System.out.println("File opened");
} catch (FileNotFoundException e) {
System.out.println("File not found");
} finally {
try {
if (file != null) {
file.close();
System.out.println("File closed");
}
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
3. throw Keyword
Manually throw an exception.
class AgeValidator {
static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
} else {
System.out.println("Valid age: " + age);
}
}
public static void main(String[] args) {
try {
validateAge(15);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
validateAge(20); // Valid age: 20
}
}
4. throws Keyword
Declares that a method might throw exceptions.
import java.io.*;
class FileHandler {
public static void readFile(String filename) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
System.out.println("First line: " + line);
reader.close();
}
public static void main(String[] args) {
try {
readFile("nonexistent.txt");
} catch (IOException e) {
System.out.println("Handled exception: " + e.getMessage());
}
}
}
5. try-with-resources (Java 7+)
Automatically closes resources.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} // br automatically closed
Multi-catch Block (Java 7+)
try {
// code that can throw multiple exceptions
} catch (IOException | SQLException e) {
System.out.println("Error: " + e.getMessage());
}
Learn robust Java programming with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
