Last mod: 2024.10.25
Checked vs unchecked exceptions
Simple diagram and short info
Exceptions in Java can be divided into two groups:
- Checked - These are exceptions that are checked at compile-time. If a method can throw a checked exception, it must either handle it using a try-catch block or declare it in the method signature using the throws keyword. Failing to do so will result in a compile-time error. Examples of checked exceptions include IOException, SQLException, and FileNotFoundException. They are usually used for recoverable conditions that the programmer is expected to handle, like file operations or network connections.
- Unchecked - These are exceptions that are not checked at compile-time but are instead checked at runtime. They are represented by subclasses of RuntimeException and include common exceptions like NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException. Unchecked exceptions are often the result of programming errors, such as invalid input or misuse of APIs, and are not expected to be explicitly handled by the programmer.
In summary, checked exceptions must be caught or declared, while unchecked exceptions can be left unhandled and are typically used for programming logic errors.
Simple examples demonstrating the use of checked exceptions with the throws keyword in Java:
public void method() throws Exception {
throw new Exception("Checked Exception");
}
public void anotherMethod() {
try {
method();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
For unchecked exceptions java compiler does not require try{}catch(...){} section or throws declaration.