Java Exception Handling Examples

Explore practical Java Exception Handling examples to enhance your coding skills and ensure robust software development.
By Jamie

Introduction to Java Exception Handling

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.

Example 1: Handling Arithmetic Exceptions

Context

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.");
        }
    }
}

Notes

  • The try block contains the code that may throw an exception.
  • The catch block handles the specific exception, providing an error message.
  • The finally block executes regardless of whether an exception occurred, making it suitable for cleanup tasks.

Example 2: Handling File Not Found Exceptions

Context

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.");
            }
        }
    }
}

Notes

  • This example includes multiple catch blocks to handle different exceptions that may arise during file operations.
  • It’s essential to close resources in the finally block to avoid memory leaks.

Example 3: Custom Exception Handling

Context

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());
        }
    }
}

Notes

  • Custom exceptions extend the Exception class, allowing for tailored error messages and conditions.
  • This approach enhances code readability and maintainability, especially in complex applications.