Java Exception Handling Cheat Sheet – Master It in Minutes
By Pramod Vishwakarma
Originally Published: December 5, 2022 | Categories: Cheat Sheet, Java, Exception Handling
When writing Java programs, unexpected events often arise: null values, bad input, or out-of-bounds arrays. These events are called exceptions, and Java provides a powerful mechanism to handle them.
This Java Exception Handling Cheat Sheet is your quick reference to mastering exception handling for development and interviews alike.
📘 What is an Exception?
An exception is an abnormal condition that disrupts the normal flow of a program during execution.
🔥 Common Java Exceptions:
NumberFormatException
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException
StackOverflowError
OutOfMemoryError
⚙️ Java Exception Handling Syntax
Java handles exceptions using three main blocks:
java
Copy
Edit
try {
// code that might throw an exception
} catch (ExceptionType e) {
// handle exception
} finally {
// this block is always executed
}
Block Breakdown:
try: Code that may throw an exception.
catch: Handles specific exceptions thrown from try.
finally: Executes regardless of whether an exception is thrown or caught (ideal for cleanup).
🔹 A try block must be followed by at least one catch or a finally.
🔹 No statements should appear between try, catch, and finally.
🔁 Multiple Catch Blocks
You can handle different exceptions using multiple catch blocks:
java
Copy
Edit
try {
int result = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Invalid number format.");
} catch (NullPointerException e) {
System.out.println("Null reference.");
}
✅ Java 7+: Multi-Catch Using |
java
Copy
Edit
try {
int result = Integer.parseInt("abc");
} catch (NumberFormatException | NullPointerException ex) {
System.out.println("Handled multiple exceptions.");
}
📌 Tip: Always order catch blocks from most specific to general. Placing a superclass (Exception) before a subclass (IOException) results in "Unreachable catch block" error.
🔄 Nested Try-Catch Blocks
Exception handling blocks can be nested to handle localized errors within a larger context:
java
Copy
Edit
try {
// Outer try
try {
// Inner try
} catch (Exception e) {
// Inner catch
}
} catch (Exception e) {
// Outer catch
}
If an inner exception isn't handled, it will propagate to the outer try-catch.
🔙 Return Values from try-catch-finally
If finally returns a value → it overrides return from try or catch.
If finally doesn’t return → try and catch must return a value.
java
Copy
Edit
public int exampleMethod() {
try {
return 1;
} catch (Exception e) {
return 2;
} finally {
return 3; // Always takes precedence
}
}
// Output: 3
✅ Checked vs Unchecked Exceptions
Feature Checked Exception Unchecked Exception
Compile-Time Checked? ✅ Yes ❌ No
Compiler Aware? ✅ Yes ❌ No
Must Handle? ✅ Yes ❌ No
Examples IOException, SQLException NullPointerException, ArithmeticException
🎯 Rule of Thumb:
Checked: Known at compile-time; must handle.
Unchecked: Known at runtime; handle defensively.
🌲 Exception Class Hierarchy
php
Copy
Edit
Throwable
├── Error
└── Exception
├── IOException (Checked)
└── RuntimeException (Unchecked)
🚀 Throw vs Throws
throw – Explicitly throw an exception
java
Copy
Edit
throw new NumberFormatException("Invalid number");
throws – Declare possible exceptions in method signature
java
Copy
Edit
public void readFile() throws IOException, SQLException {
// code that might throw IOException or SQLException
}
🧰 Try-With-Resources (Java 7+)
Auto-closes resources (like streams, readers):
java
Copy
Edit
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
⚠️ Java 7 Limitation:
Resources must be declared inside try.
Java 9+ allows pre-declared resources to be used.
✅ Key Takeaways
Handle exceptions to prevent app crashes.
Always close resources (use finally or try-with-resources).
Know the difference between checked and unchecked exceptions.
Practice writing clean, layered catch blocks.
🎓 Interview Prep Tips
Be able to explain exception flow: try → catch → finally.
Demonstrate multi-catch and nested try-catch in examples.
Know when and why to use throw and throws.
Show practical use of try-with-resources in file or DB operations.
Comments
Post a Comment