Java Exceptions
An exception is an event that disrupts the normal flow of a program, such as dividing by zero or accessing an invalid array index. Java handles exceptions using try, catch, finally, and throw.
Exceptions are either checked (must be declared or caught, like IOException) or unchecked (RuntimeException subclasses, like NullPointerException), which don't require explicit handling.
try {
} catch (Exception e) {
} finally {
}try, catch, finally
Code that might throw an exception goes in a try block; catch blocks handle specific exception types; finally always runs, whether or not an exception occurred.
Checked vs unchecked
Checked exceptions must be declared with `throws` or handled; unchecked exceptions (RuntimeException and subclasses) do not require this.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Done");
}
}
}Error: / by zero
DoneDividing by zero throws an ArithmeticException, which is caught, then finally always runs.
Key points
- try/catch handles exceptions gracefully.
- finally always executes, error or not.
- Checked exceptions must be declared or handled.
- throw lets you raise your own exceptions.
