Java Exception Handling

Handle runtime errors gracefully using try-catch blocks, throw, throws, and custom exceptions.

Exception Handling in Java allows applications to gracefully handle runtime errors and continue execution without crashing.

1. Try and Catch

The try block encloses code that may throw an exception. The catch block handles it.

public class TryCatchDemo {
    public static void main(String[] args) {
        try {
            int[] arr = {10, 20, 30};
            System.out.println(arr[5]); // Causes ArrayIndexOutOfBoundsException
        } catch (Exception e) {
            System.out.println("Error occurred: " + e.getMessage());
        }
    }
}

2. Finally Block

The finally block executes whether an exception occurs or not. Useful for closing files, database connections, or releasing resources.

public class FinallyDemo {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
            int divide = 10 / 0; // Throws error
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("Finally always executes");
        }
    }
}

3. The throw Keyword

The throw keyword is used to manually throw an exception.

public class ThrowDemo {

    static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Access denied – You must be at least 18.");
        } else {
            System.out.println("Access granted");
        }
    }

    public static void main(String[] args) {
        checkAge(15);
    }
}

4. The throws Keyword

The throws keyword declares that a method may throw an exception. The calling method must handle it.

import java.io.IOException;

public class ThrowsDemo {

    static void readData() throws IOException {
        throw new IOException("Unable to read data");
    }

    public static void main(String[] args) {
        try {
            readData();
        } catch (IOException e) {
            System.out.println("Handled IOException: " + e.getMessage());
        }
    }
}

5. Checked vs Unchecked Exceptions

Checked Exceptions: Occur at compile-time (e.g., IOException, SQLException).

Unchecked Exceptions: Occur at runtime (e.g., NullPointerException, ArithmeticException).

6. Creating a Custom Exception

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class CustomExceptionDemo {

    static void validate(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Custom Error: Age must be 18 or above");
        }
        System.out.println("Valid Age!");
    }

    public static void main(String[] args) {
        try {
            validate(15);
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }
}

Sidebar Ad Space
Advertisement Space