INSTACK 360

Java Exception Handling

Write resilient Java applications by elegantly catching, throwing, and handling runtime exceptions.

Advanced 5 min read

What is an Exception?

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs, the normal flow of the program is disrupted and the program/Application terminates abnormally.

The try-catch Block

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.

try {
    int[] myNumbers = {1, 2, 3};
    System.out.println(myNumbers[10]); // This will generate an exception
} catch (Exception e) {
    System.out.println("Something went wrong.");
}

The finally Block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. It is mainly used to close connections or files.

try {
    // code
} catch (ExceptionType name) {
    // code
} finally {
    // Always executed
}

The throws/throw Keywords

  • throw: Used to explicitly throw an exception from within a method.
  • throws: Used in the method signature to declare that this method might throw exceptions.