Abstract
- Many modern programming languages support exceptions.
- The
catchblocks are checked in the order they appear. The first compatiblecatchblock handles the exception. finallyis optional and used for housekeeping tasks (e.g., closing resources)finallyis always executed, even if there’s an exception or areturnin thetryorcatchblocks
3 possible execution outcome
Normal Execution:
tryblock executes without errors, thenfinallyblock executes.Error Execution: If an error occurs in the
tryblock, execution jumps to the first compatiblecatchblock, then thefinallyblock executes.Passing the Buck: The caller can pass the exception up the call stack until it’s caught. Unchecked exceptions propagate automatically. Checked exceptions must be handled or declared.
Good practices
Do NOT Return from Finally: Can lead to counter-intuitive behaviour and lost exceptions.
Do NOT Use Exception As a Control Flow Mechanism: Use
if-elsefor normal program logic, not exceptions.Do NOT Break Abstraction Barrier: Handle implementation-specific exceptions within the class to avoid leaking details to the caller.
Catch Exceptions to Clean Up: Handle exceptions to release resources, even if you re-throw the exception.
Do NOT Catch-Them-All!: Avoid catching
Exceptionto prevent silently ignoring all exceptions.Do NOT Overreact: Don’t exit the program just because of an exception.
Raising Exception
- Use the
throwskeyword in the method declaration to indicate that the method might throw an exception. - Create a new exception object and
throwit to the caller. - Executing the
throwstatement causes the method to immediately return.
Unchecked Exceptions
- Caused by programmer errors (e.g.,
IllegalArgumentException,NullPointerException)
Important
Generally not explicitly caught or thrown.
Unchekd exceptions in Java
Subclasses of
RuntimeException.
Checked Exceptions
- Programmer has no control over them (e.g.,
FileNotFoundException)
Must be handled or declared
Must be either handled or declared in the method signature using
throws, or we can’t pass compilation checks.
Java Exception

- Exceptions are instances that are a subtype of the
Exceptionclass. Information about an exception is encapsulated in an exception instance and “passed” into thecatchblock - Inherit from an existing exception class if you need to provide additional information or behaviour
The
ErrorclassUsed for unrecoverable situations (e.g.,
OutOfMemoryError). Typically don’t need to create or handleError.
Important
Only handles one
catch()block!Exceptions can be handled with a catch block that catches its supertype.
