Exception Handling in Java

Exception handling in Java is a mechanism to manage runtime errors and ensure the smooth flow of a program. It helps developers handle unexpected situations gracefully.

What is an Exception?

An exception is an event that occurs during the execution of a program, disrupting its normal flow. It is represented as an object that Java throws at runtime.


public class Example {
    public static void main(String[] args) {
        int result = 10 / 0; // Throws ArithmeticException
    }
}
      

Need for Exception Handling

Exception handling is essential for managing errors and maintaining the normal flow of the program. It ensures:

Handling Exceptions Using try and catch Block

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


try {
    int result = 10 / 0; // Risky code
} catch (ArithmeticException e) {
    System.out.println("Error: Division by zero.");
}
      

Exception Hierarchy Diagram

Exception Hierarchy
Java Exception Hierarchy

Exception vs Error

Types of Exceptions

Checked Exceptions

These exceptions are checked at compile-time and must be declared in the method signature using throws.


try {
    FileReader reader = new FileReader("file.txt"); // Checked Exception
} catch (IOException e) {
    e.printStackTrace();
}
      

Unchecked Exceptions

Unchecked exceptions are checked at runtime and are not verified by the compiler.


String str = null;
System.out.println(str.length()); // NullPointerException
      

Unchecked Exception Scenarios

Checked Exception Scenarios

Handling Unchecked Exceptions Using Preconditions


int divisor = 0;
if (divisor != 0) {
    int result = 10 / divisor;
} else {
    System.out.println("Error: Divisor cannot be zero.");
}
      

Exception Handling Keywords

throw Keyword

The throw keyword is used to explicitly throw an exception.


public class ThrowExample {
    public static void main(String[] args) {
        throw new ArithmeticException("Manually thrown exception.");
    }
}
      

Exception Propagation

Exception propagation refers to passing exceptions from one method to another. It applies to both checked and unchecked exceptions.

Checked Exception Propagation


void method1() throws IOException {
    FileReader file = new FileReader("file.txt");
}
void method2() throws IOException {
    method1();
}
      

Unchecked Exception Propagation


void method1() {
    int result = 10 / 0; // ArithmeticException
}
void method2() {
    method1();
}
      

Customized Exceptions

Customized Checked Exception


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

Customized Unchecked Exception


class CustomUncheckedException extends RuntimeException {
    public CustomUncheckedException(String message) {
        super(message);
    }
}
      

Summary

Keyword Description
try Defines the block of code to test for exceptions.
catch Handles exceptions.
finally Executes cleanup code after try/catch.
throw Used to explicitly throw an exception.
throws Declares exceptions in a method signature.