Skip to content

Exception Handling

Exception Handling in Java is a mechanism to handle runtime errors, ensuring the program can continue executing or fail gracefully. This mechanism is crucial for building robust and error-tolerant applications.


What is an Exception?

An exception is an unexpected event that disrupts the normal flow of a program during runtime. It can occur due to:

  1. User errors (e.g., invalid input).
  2. Programming errors (e.g., division by zero).
  3. System errors (e.g., file not found).

Hierarchy of Exceptions

In Java, exceptions are objects of the class java.lang.Exception or its subclasses. The hierarchy is as follows:

  1. Throwable (Base class)
    1. Exception (Recoverable errors)
      1. Checked Exceptions (e.g., IOException, SQLException)
      1. Unchecked Exceptions (e.g., ArithmeticException, NullPointerException)
    1. Error (Non-recoverable errors, e.g., OutOfMemoryError, StackOverflowError)

Why Use Exception Handling?

  1. Improves Code Readability:
    1. Separates error-handling code from regular logic.
  2. Ensures Program Continuity:
    1. Handles unexpected situations without crashing.
  3. Facilitates Debugging:
    1. Provides detailed stack traces to diagnose issues.

Key Concepts in Exception Handling

1. Try-Catch Block

  • The try block contains the code that might throw an exception.
  • The catch block handles the exception.

try {

    // Code that may throw an exception

} catch (ExceptionType e) {

    // Code to handle the exception

}

Example:

public class ExceptionExample {

    public static void main(String[] args) {

        try {

            int result = 10 / 0; // May throw ArithmeticException

        } catch (ArithmeticException e) {

            System.out.println(“Cannot divide by zero.”);

        }

        System.out.println(“Program continues…”);

    }

}

Output:

Cannot divide by zero.

Program continues…


2. Multiple Catch Blocks

You can handle different exceptions separately.

try {

    int[] numbers = {1, 2, 3};

    System.out.println(numbers[3]); // ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {

    System.out.println(“Arithmetic error occurred.”);

} catch (ArrayIndexOutOfBoundsException e) {

    System.out.println(“Array index is out of bounds.”);

}


3. Finally Block

  • A finally block contains code that will execute whether or not an exception occurs.
  • Typically used for cleanup (e.g., closing resources).

try {

    int result = 10 / 2;

    System.out.println(“Result: ” + result);

} catch (ArithmeticException e) {

    System.out.println(“Error occurred.”);

} finally {

    System.out.println(“Execution of finally block.”);

}

Output:

Result: 5

Execution of finally block.


4. Throw Keyword

  • Used to explicitly throw an exception.

public class ThrowExample {

    static void checkAge(int age) {

        if (age < 18) {

            throw new ArithmeticException(“Access denied – You must be at least 18 years old.”);

        } else {

            System.out.println(“Access granted.”);

        }

    }

    public static void main(String[] args) {

        checkAge(16);

    }

}

Output:

Exception in thread “main” java.lang.ArithmeticException: Access denied – You must be at least 18 years old.


5. Throws Keyword

  • Used in method declarations to specify exceptions that a method might throw.

import java.io.IOException;

public class ThrowsExample {

    static void readFile() throws IOException {

        throw new IOException(“File not found.”);

    }

    public static void main(String[] args) {

        try {

            readFile();

        } catch (IOException e) {

            System.out.println(“Exception caught: ” + e.getMessage());

        }

    }

}


Types of Exceptions

  1. Checked Exceptions:
    1. Known at compile-time.
    1. Example: IOException, SQLException.
  2. Unchecked Exceptions:
    1. Known at runtime.
    1. Example: ArithmeticException, NullPointerException.

Custom Exceptions

You can create your own exception by extending the Exception or RuntimeException class.

class CustomException extends Exception {

    public CustomException(String message) {

        super(message);

    }

}

public class CustomExceptionExample {

    public static void main(String[] args) {

        try {

            throw new CustomException(“This is a custom exception.”);

        } catch (CustomException e) {

            System.out.println(e.getMessage());

        }

    }

}


Best Practices for Exception Handling

  1. Handle Specific Exceptions:
    1. Avoid using generic Exception unless necessary.
  2. Use Finally for Cleanup:
    1. Always release resources in the finally block.
  3. Don’t Swallow Exceptions:
    1. Avoid empty catch blocks.
  4. Use Custom Exceptions:
    1. Create meaningful exceptions to make debugging easier.
  5. Avoid Overusing Checked Exceptions:
    1. Use unchecked exceptions for programming logic errors.

Conclusion

Exception handling in Java ensures robust and reliable application development by effectively managing runtime errors. By following best practices, developers can write clean, maintainable, and error-resilient code.