Java Exception Handling
Understanding the Exception Hierarchy and Try-Catch Blocks
What are Exceptions in Java and Why They Matter
What is an Exception? Why Exception Handling Matters
An exception is an unexpected event that disrupts the normal • Prevents programme crashes and unexpected termination
flow of programme execution. When an error occurs during • Provides meaningful error messages to users and developers
runtime, Java creates an exception object containing
• Enables graceful recovery from runtime errors
information about the error, including its type and programme
• Separates error-handling code from regular business logic
state.
The Complete Java Exception Hierarchy Structure
Java's exception architecture is built on a well-defined class hierarchy that organises all exception types systematically.
Error RuntimeException (unchecked)
Serious JVM problems like
OutOfMemoryError
NullPointerException, ArithmeticException,
ClassCastException
Throwable
IOException (checked) SQLException (checked)
FileNotFoundException, EOFException, SQLIntegrityConstraintViolationException,
InterruptedIOException SQLTimeoutException
Throwable Class
The Root of All Exceptions
Superclass Foundation Key Methods Two Main Branches
Throwable is the ultimate parent getMessage() - Returns detailed Throwable has two direct
class for all errors and error message subclasses: Error (for serious
exceptions in Java. Every object printStackTrace() - Prints system problems) and
that can be thrown or caught stack trace to console Exception (for conditions that
must be an instance of this class programmes should catch and
getCause() - Returns the
or its subclass. handle).
underlying cause
Error vs Exception
Understanding the Key Differences
Error Exception
Serious problems that applications should not attempt to Recoverable conditions that well-written applications
catch. These represent abnormal conditions from which should anticipate and handle gracefully to maintain
recovery is typically impossible. programme stability.
Characteristics:
Characteristics:
• Can and should be caught and handled
• Cannot be handled or recovered from • Represents recoverable conditions
• Indicates serious JVM or system issues • May be checked or unchecked
• Not checked at compile time
Common Examples:
Common Examples:
• IOException
• OutOfMemoryError • SQLException
• StackOverflowError • NullPointerException
• VirtualMachineError
Checked vs Unchecked Exceptions
Classification and Examples
Checked Exceptions Unchecked Exceptions
Compile-time exceptions that must be explicitly handled or Runtime exceptions that occur during programme execution
declared. The compiler verifies these at compile time, forcing and aren't checked at compile time. These typically indicate
developers to acknowledge potential failures. programming errors or logical mistakes in code.
Examples: IOException, SQLException, Examples: NullPointerException, ArithmeticException,
ClassNotFoundException, FileNotFoundException ArrayIndexOutOfBoundsException,
IllegalArgumentException
Must use try-catch or throws declaration No compile-time enforcement required
Try-Catch Block Syntax
Basic Structure and Components
Structure Overview Basic Syntax
The try-catch mechanism allows you to test a block of
try { // Code that may throw exception int
code for errors, catch those errors, and execute
result = 10 / 0; [Link](result);} catch
alternative code when exceptions occur.
(ArithmeticException e) { // Exception handling
Key Components: code [Link]("Error: " +
[Link]()); [Link]("Cannot divide
try - Contains code that might throw an exception by zero");}
catch - Handles the exception if it occurs
finally - Executes regardless of exception (optional)
Important: The try block must be followed by either a catch block, a finally block, or both. Without at least one of
these, the code will not compile.
Multiple Catch Blocks
Handling Different Exception Types
Java allows multiple catch blocks to handle different types of exceptions separately, enabling specific error-handling strategies for each exception type.
01 02
Specific to General Order Multi-Catch Feature
Catch blocks must be ordered from most specific to most general exception Java 7+ allows catching multiple exception types in a single catch block using
types, as Java checks them sequentially. the pipe (|) operator.
Multiple Catch Blocks Multi-Catch Syntax
try { int[] arr = {1, 2, 3}; [Link](arr[5]); try { // Code that may throw exceptions performOperation();}
int result = 10 / 0;} catch (ArrayIndexOutOfBoundsException catch (IOException | SQLException e) { // Handle both
e) { [Link]("Array index error");} catch exceptions [Link]("Database or file error");
(ArithmeticException e) { [Link]("Arithmetic [Link]();}
error");} catch (Exception e) { [Link]("General
error");}
Finally Block
Ensuring Code Execution Regardless of Exceptions
Guaranteed Execution Resource Management Try-With-Resources
The finally block always executes whether an Commonly used to release system resources, ensuring Java 7 introduced try-with-resources as an alternative
exception occurs or not, making it perfect for cleanup that critical cleanup code runs even if an exception that automatically closes resources, reducing
operations like closing files, database connections, or disrupts normal programme flow. boilerplate finally block code.
network sockets.
Complete Try-Catch-Finally Example
FileReader reader = null;try { reader = new FileReader("[Link]"); // Read file content int data = [Link]();} catch (FileNotFoundException e)
{ [Link]("File not found: " + [Link]());} catch (IOException e) { [Link]("Error reading file: " + [Link]());}
finally { // This block always executes try { if (reader != null) [Link](); } catch (IOException e) { [Link]("Error closing
file"); }}
Best Practices
Exception Handling Guidelines for Robust Java Applications
Catch Specific Exceptions Provide Meaningful Messages
Always catch the most specific exception type possible rather than using Include descriptive error messages that help identify the problem quickly. Log
generic Exception class. This enables precise error handling and better exceptions with sufficient context for troubleshooting production issues.
debugging.
Clean Up Resources Don't Swallow Exceptions
Always release resources in finally blocks or use try-with-resources statements. Never catch exceptions without handling them appropriately. Empty catch
Failing to close resources can lead to memory leaks and system instability. blocks hide problems and make debugging extremely difficult in production
environments.
Document Exceptions Create Custom Exceptions
Use @throws Javadoc tags to document which exceptions methods can throw. Define custom exception classes for application-specific errors. This makes your
This helps other developers understand and properly handle potential errors. code more readable and enables domain-specific error handling strategies.