Java Exception Handling


Java Exception Handling

Java Exception Handling is a crucial mechanism in the Java programming language that allows developers to handle runtime errors systematically. It helps maintain the normal flow of a program even when unexpected situations, called exceptions, arise. Below is a detailed explanation of exception handling in Java, along with syntax and examples.


What is an Exception?

In Java, an exception is an event that interrupts a program's normal flow during execution and requires special handling.

  • Division by zero
  • Accessing an invalid array index
  • Attempting to open a file that doesn’t exist

Types of Exceptions

  • Checked Exceptions: These are checked at compile time. Examples: IOException, SQLException.
  • Unchecked exceptions occur at runtime and are not verified during compilation. Examples: ArithmeticException, NullPointerException.
  • Errors: Represent severe issues that the program cannot typically handle. Examples: OutOfMemoryError, StackOverflowError

Key Components of Exception Handling

  • Try block: Contains code that may trigger an exception.
  • Catch block: Captures and manages exceptions if they occur.
  • Finally block: Executes in all cases, whether an exception is thrown or not.
  • throw keyword: Explicitly generates an exception.
  • throws keyword: Declares exceptions a method might generate.

Syntax of Exception Handling

try {
    // Code that may result in an exception.
} catch (ExceptionType1 e1) {
    // Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle exception of type ExceptionType2
} finally {
    // Code that will always execute
}

Example: Division by Zero

Following example is for handle an Arithmetic Exception using a try-catch block.

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int result = a / b; // This triggers an ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Division by zero error: " + e.getMessage());
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

Output:

Cannot divide by zero: / by zero
Execution completed.

throw Keyword Example

The throw keyword is used to manually generate an exception.

public class ThrowExample {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("age must be 18 or more than 18.");
        }
        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Exception:age must be 18 or more than 18.

throw Keyword Example

The throw keyword is used to manually generate an exception.

public class ThrowExample {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("age must be 18 or more than 18.");
        }
        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Exception: age must be 18 or more than 18.

throws Keyword Example

The throws keyword specifies the exceptions a method might generate.

import java.io.*;

public class ThrowsExample {
    public static void readFile() throws IOException {
        FileReader file = new FileReader("nonexistent.txt");
        BufferedReader br = new BufferedReader(file);
        System.out.println(br.readLine());
        br.close();
    }

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

Output:

File not Exist: nonexistent.txt (No such file or directory).

finally Block Example

This example shows how to manage an Arithmetic Exception using a try-catch block.

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds.");
        } finally {
            System.out.println("This block will always execute.");
        }
    }
}

Output:

Array index is out of bounds.
This block will always execute.

Custom Exceptions

Custom exception classes can be created by extending either Exception or RuntimeException.

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

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            validateNumber(0);
        } catch (CustomException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    public static void validateNumber(int num) throws CustomException {
        if (num <= 0) {
            throw new CustomException("Number must be positive.");
        }
        System.out.println("Valid number: " + num);
    }
}

Output:

Caught exception: Number must be positive.

Best Practices for Exception Handling

  • Catch specific exceptions instead of generic ones.
  • Use finally for cleanup code like closing resources.
  • Avoid using exceptions for flow control.
  • Log exceptions for debugging.
  • Provide meaningful exception messages.
PreviousNext