Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. try / catch / finally / throw

try / catch / finally / throw

The basic syntax for exception handling. Wrap code that may throw an exception in a try block, and handle the exception in a catch block. The finally block always executes regardless of whether an exception occurred.

Syntax

// Basic exception handling syntax.
try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that always runs, with or without an exception
}

// Catching multiple exceptions separately.
try {
    // Code
} catch (IOException e) {
    // Handle IOException
} catch (NumberFormatException e) {
    // Handle NumberFormatException
}

// Catching multiple exceptions in a single catch (Java 7+).
try {
    // Code
} catch (IOException | NumberFormatException e) {
    // Handle multiple exceptions together
}

// Throwing an exception explicitly.
throw new IllegalArgumentException("Invalid value.");

// Propagating a checked exception to the caller.
public void readFile() throws IOException {
    // Code that may throw IOException
}

Common Exception Classes

ClassDescription
ExceptionThe base class for checked exceptions. Requires a throws declaration.
RuntimeExceptionThe base class for unchecked exceptions. No throws declaration needed.
IOExceptionA checked exception for I/O operations.
NullPointerExceptionThrown when accessing a null object reference.
IllegalArgumentExceptionAn unchecked exception thrown when an argument is invalid.
NumberFormatExceptionThrown when a string cannot be converted to a number.
ArrayIndexOutOfBoundsExceptionThrown when accessing an array index out of bounds.

Sample Code

// Basic exception handling.
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage()); // Prints "Error: / by zero"
} finally {
    System.out.println("The finally block executed.");
}

// Catching multiple exceptions.
String input = "abc";
try {
    int num = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Cannot convert to number: " + input);
} catch (Exception e) {
    System.out.println("Unexpected error: " + e.getMessage());
}

// Throwing an exception with throw.
public static int divide(int a, int b) {
    if (b == 0) {
        throw new IllegalArgumentException("Divisor cannot be zero.");
    }
    return a / b;
}

// Propagating an exception to the caller with throws.
public static String readFirstLine(String path) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    return br.readLine();
}

Notes

Java exceptions fall into two categories: checked exceptions and unchecked exceptions. The compiler enforces that checked exceptions (classes that directly extend Exception) are either caught with try-catch or declared with throws to propagate them to the caller. Unchecked exceptions (subclasses of RuntimeException) are optional to handle.

The finally block has traditionally been used to release resources (such as closing files), but since Java 7, you can write this more concisely using 'try-with-resources'. Be mindful of the exception class hierarchy — always place more specific exception types before more general ones in your catch blocks.

To automatically close resources, use 'try-with-resources / AutoCloseable'.

If you find any errors or copyright issues, please .