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
| Class | Description |
|---|---|
| Exception | The base class for checked exceptions. Requires a throws declaration. |
| RuntimeException | The base class for unchecked exceptions. No throws declaration needed. |
| IOException | A checked exception for I/O operations. |
| NullPointerException | Thrown when accessing a null object reference. |
| IllegalArgumentException | An unchecked exception thrown when an argument is invalid. |
| NumberFormatException | Thrown when a string cannot be converted to a number. |
| ArrayIndexOutOfBoundsException | Thrown 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 contact us.