What is Exception Handling in Java?: try, catch, throw, finally

Exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can continue instead of crashing abruptly.

Key Keywords

  • try — wraps the code that might throw an exception
  • catch — handles the exception thrown by the try block
  • throw — used to explicitly throw an exception
  • throws — declares that a method might throw an exception
  • finally — a block that always executes, whether an exception occurred or not

Basic Example

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
    System.out.println("This block always runs");
}

Throwing a Custom Exception

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

void checkAge(int age) throws InvalidAgeException {
    if (age < 18) {
        throw new InvalidAgeException("Age must be 18 or above");
    }
}

Types of Exceptions

  • Checked Exceptions — checked at compile time, such as IOException
  • Unchecked Exceptions — occur at runtime, such as NullPointerException and ArithmeticException
  • Errors — serious problems like OutOfMemoryError that applications usually shouldn't try to catch
You can use multiple catch blocks after a single try to handle different exception types differently, and Java also supports a multi-catch syntax using the pipe (|) operator.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course