What is exception handling?
Solution and explanation
What it is
An exception is an event that disrupts the normal flow of a program at run time: a missing file, a network failure, dividing by zero, a null reference. Exception handling is the mechanism to detect such events, respond to them and keep the program running (or fail cleanly) instead of crashing.
Without handling
int[] marks = {80, 90};
System.out.println(marks[5]); // ArrayIndexOutOfBoundsException → program stops
System.out.println("Never printed");
With handling
try {
int amount = Integer.parseInt(input); // may throw NumberFormatException
double perHead = amount / members; // may throw ArithmeticException
System.out.println(perHead);
} catch (NumberFormatException e) {
System.out.println("Please enter digits only");
} catch (ArithmeticException e) {
System.out.println("Group must have at least one member");
} finally {
System.out.println("Split calculation finished"); // always runs
}
The keywords
| Keyword | Purpose |
|---|---|
| try | Wraps code that might throw |
| catch | Handles a specific exception type |
| finally | Runs whether or not an exception occurred (cleanup) |
| throw | Throws an exception object |
| throws | Declares exceptions a method may pass to its caller |
How it works
- An exception object is created with the type, message and stack trace.
- The JVM looks for a matching catch in the current method, then in its caller, up the call stack.
- If none is found, the thread terminates and the stack trace is printed.
Multi-catch (Java 7+)
catch (IOException | SQLException e) { log.error("Data access failed", e); }
Best practices
- Catch specific exceptions, not
ExceptionorThrowableblindly. - Never swallow exceptions with an empty catch block.
- Log with the exception object to keep the stack trace.
- Use try-with-resources for anything that must be closed.
- In Spring REST APIs, map exceptions to HTTP responses centrally with
@RestControllerAdvice.
