Java Exception Handling is a powerful mechanism that allows developers to manage runtime errors, ensuring that applications remain stable and user-friendly. By utilizing try-catch blocks, developers can catch exceptions, handle them gracefully, and maintain control over program flow. Below are three diverse and practical examples that illustrate different aspects of Java Exception Handling.
In any application involving calculations, it’s crucial to handle potential arithmetic errors, such as division by zero. This example demonstrates how to catch and handle an ArithmeticException
.
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}
}
}
try
block contains the code that may throw an exception.catch
block handles the specific exception, providing an error message.finally
block executes regardless of whether an exception occurred, making it suitable for cleanup tasks.When working with file operations, it’s common to encounter FileNotFoundException
. This example shows how to properly handle this exception when attempting to read a file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
String filePath = "non_existent_file.txt";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("Error: File not found! Please check the file path.");
} catch (IOException e) {
System.out.println("Error: An I/O error occurred.");
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("Error: Failed to close the reader.");
}
}
}
}
catch
blocks to handle different exceptions that may arise during file operations.finally
block to avoid memory leaks.Creating custom exceptions can improve error handling in applications, allowing developers to define specific error conditions. This example illustrates how to create and throw a custom exception.
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
}
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Exception
class, allowing for tailored error messages and conditions.