Exception Overview
Exceptions represent disruptive events occurring during application execution that, if unresolved, typically lead to the abrupt termination of the JVM.
Exception Classification
- Checked Exceptions (Compile-time): These are verified during the compilation phase. Developers must explicitly handle or declare them; otherwise, the compilation process fails. Examples include
IOExceptionor custom data parsing errors. - Unchecked Exceptions (Runtime): These are evaluated during application execution. The compiler does not enforce their handling at compile time.
RuntimeExceptionand its subclasses (such asArithmeticExceptionorNullPointerException) fall into this group.
Exception Handling Mechanisms
Java provides five core keywords to manage error flows: try, catch, finally, throw, and throws.
Declaring Exceptions with throws
When a method might encounter a failure, it can propagate the exception to its caller via the throws clause, deferring immediate handling.
public class FileProcessor {
public static void main(String[] args) throws IllegalArgumentException {
validateConfig("default.properties");
}
public static void validateConfig(String configName) throws IllegalArgumentException {
if (!"app.properties".equals(configName)) {
throw new IllegalArgumentException("Required configuration file is missing");
}
}
}Capturing Exceptions with try...catch
To handle failures immediately, enclose the potentially unsafe logic within a try block, followed by a catch block resolving the specific error type.
public class ConfigurationLoader {
public static void main(String[] args) {
try {
validateConfig("user.settings");
} catch (IllegalArgumentException err) {
System.err.println(err.getMessage());
}
System.out.println("Application proceeds");
}
public static void validateConfig(String configName) throws IllegalArgumentException {
if (!"app.properties".equals(configName)) {
throw new IllegalArgumentException("Required configuration file is missing");
}
}
}The finally Block
A finally block guarantees the execution of its code regardless of whether an exception was thrown. It bypasses the normal jump behavior associated with exceptions, ensuring resource cleanup or finalization tasks are completed.
Crucial Behavior: If a return statement is encountered within the try or catch scope, the JVM executes the finally block before actually transferring control back to the invoking method.