CodeToLive

Exception Handling in Java

Exception handling in Java allows you to handle errors gracefully and prevent your program from crashing. It is a powerful mechanism that ensures the normal flow of the application even when unexpected events occur.

Try-Catch Block

Use the try and catch blocks to catch and handle exceptions. The try block contains the code that might throw an exception, and the catch block contains the code to handle the exception.


public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
    }
}
      

Finally Block

The finally block is executed regardless of whether an exception occurs. It is typically used for cleanup activities, such as closing files or releasing resources.


public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        } finally {
            System.out.println("This will always execute.");
        }
    }
}
      

Custom Exceptions

You can define custom exceptions by creating a new class that extends Exception. This allows you to create specific exception types for your application.


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

public class Main {
    public static void main(String[] args) {
        try {
            throw new CustomException("This is a custom exception");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}
      

Multiple Catch Blocks

You can have multiple catch blocks to handle different types of exceptions. The first matching catch block will be executed.


public class Main {
    public static void main(String[] args) {
        try {
            int[] arr = new int[5];
            arr[10] = 50; // This will throw an ArrayIndexOutOfBoundsException
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurred");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array Index Out Of Bounds Exception occurred");
        } catch (Exception e) {
            System.out.println("Some other exception occurred");
        }
    }
}
      

Throwing Exceptions

You can throw exceptions explicitly using the throw keyword. This is useful when you want to indicate that an error condition has occurred.


public class Main {
    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (ArithmeticException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }

    static void validateAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Not valid");
        } else {
            System.out.println("Welcome to vote");
        }
    }
}
      

Exception Propagation

Exceptions can be propagated from one method to another. If a method does not handle an exception, it is passed to the calling method.


public class Main {
    public static void main(String[] args) {
        try {
            method1();
        } catch (Exception e) {
            System.out.println("Exception caught in main method: " + e.getMessage());
        }
    }

    static void method1() throws Exception {
        method2();
    }

    static void method2() throws Exception {
        throw new Exception("Exception thrown in method2");
    }
}
      
Next: Collections