Exception Handling
try-catch-finally, checked vs unchecked, custom exceptions, throw vs throws
- Understand the exception hierarchy in Java
- Differentiate between checked and unchecked exceptions
- Master try-catch-finally, throw, and throws
- Create and use custom exceptions
*Java Basics to Advanced | Lecture Exception Handling*
Table of Contents
- What is an Exception?
- Exception Object and Stack Trace
- Exception Hierarchy
- Error vs. Exception
- Checked vs. Unchecked Exceptions
- Basic try-catch
- Multiple catch Blocks
- Catching Parent Exceptions — Order Matters
- Multiple Exceptions in One catch Block
- The
finallyBlock - The
throwKeyword - The
throwsKeyword throwvs.throws— Complete Comparison- Custom (User-Defined) Exceptions
- Handling Runtime Exceptions (Optional but Recommended)
- Advantages of Exception Handling
- When to Avoid Exception Handling
- Common Runtime Exceptions — Reference
- Summary Diagrams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Quick Revision Summary
1. What is an Exception?
Definition
An exception is an event that occurs during the execution of a program that disrupts its normal flow of instructions.
When Java encounters an exceptional condition — dividing by zero, accessing an array index that doesn't exist, trying to use a null reference — it creates a special object that describes the problem. This object is called an exception object, and the act of creating and signaling this event is called throwing an exception.
Real-World Analogy
Think of your program as a car on a highway. Normal execution is smooth driving. An exception is a sudden roadblock — the car cannot continue on its current path. Exception handling is your detour plan: a pre-defined alternate route that lets you reach your destination despite the obstruction.
Normal Flow vs. Exceptional Flow
1Normal Flow:2main() → method1() → method2() → method3() → completes normally → returns to main() → program ends3
4Exceptional Flow:5main() → method1() → method2() → method3() → EXCEPTION OCCURS6 ↓7 Exception object created8 ↓9 JVM searches for handler10 (method3 → method2 → method1 → main)11 ↓12 If no handler found → program terminates abruptly13 If handler found → exception handled → continues2. Exception Object and Stack Trace
What Is an Exception Object?
When an exception occurs, the Java runtime system automatically creates an exception object containing three key pieces of information:
| Field | What It Contains | Example |
|---|---|---|
| Type | The class of the exception | ArithmeticException |
| Message | Human-readable description of the problem | "/ by zero" |
| Stack Trace | The chain of method calls from where the error occurred back to main() | See below |
The Stack Trace Explained
The stack trace is the most valuable debugging tool Java gives you. It shows the exact path execution took from the program entry point to the point where the exception occurred.
Example Code
1public class Main {2 public static void main(String[] args) {3 method1(); // line 64 }5
6 static void method1() {7 method2(); // line 108 }9
10 static void method2() {11 method3(); // line 1412 }13
14 static void method3() {15 int result = 5 / 0; // line 18 ← exception here16 }17}Output (Program Terminates)
1Exception in thread "main" java.lang.ArithmeticException: / by zero2 at Main.method3(Main.java:18) ← where exception ACTUALLY happened3 at Main.method2(Main.java:14) ← method3 was called from here4 at Main.method1(Main.java:10) ← method2 was called from here5 at Main.main(Main.java:6) ← method1 was called from hereReading the Stack Trace
1java.lang.ArithmeticException: / by zero2 ↑ Type of exception ↑ Message3
4at Main.method3(Main.java:18)5 ↑ Class name ↑ Method name ↑ File ↑ Line number- Read from top to bottom: the top entry is where the exception originated
- Read from bottom to top: to see how execution arrived at the error point
- Line numbers tell you exactly where to look in your source code
How JVM Searches for a Handler
When an exception is thrown, JVM traverses the call stack looking for a method that can handle it:
3. Exception Hierarchy
Java organizes all exceptions and errors in a class hierarchy rooted at java.lang.Object:
1java.lang.Object2 └── java.lang.Throwable3 ├── java.lang.Error ← NOT for us to handle4 │ ├── OutOfMemoryError5 │ ├── StackOverflowError6 │ └── (other JVM errors)7 │8 └── java.lang.Exception ← We handle these9 ├── RuntimeException ← Unchecked (runtime)10 │ ├── ArithmeticException11 │ ├── ClassCastException12 │ ├── NullPointerException13 │ ├── IndexOutOfBoundsException14 │ │ ├── ArrayIndexOutOfBoundsException15 │ │ └── StringIndexOutOfBoundsException16 │ ├── NumberFormatException17 │ └── IllegalArgumentException18 │19 ├── ClassNotFoundException ← Checked (compile-time)20 ├── InterruptedException21 ├── IOException22 │ └── FileNotFoundException23 └── (other checked exceptions)Throwable is the parent of both Error and Exception
2. RuntimeException (and its subclasses) are unchecked; everything else under Exception is checked4. Error vs. Exception
This is one of the most frequently asked interview questions on this topic.
Error
Errors
represent serious problems related to the JVM environment that are outside the control of the application. You should not try to catch or handle Errors.
Examples
1// OutOfMemoryError — heap is exhausted2String[] hugArray = new String[Integer.MAX_VALUE]; // JVM can't allocate this3// → java.lang.OutOfMemoryError: Java heap space4
5// StackOverflowError — stack is exhausted (infinite recursion)6public static void recurse() {7 recurse(); // calls itself forever8}9recurse();10// → java.lang.StackOverflowErrorWhy You Should Not Handle Errors
- They indicate that the JVM itself is in an unhealthy state
- Even if you caught one, you likely couldn't do anything meaningful to fix it
- The recommended approach is to let the JVM terminate and fix the root cause (increase heap size, fix infinite recursion, etc.)
Exception
Exceptions
represent problems in application code that can often be anticipated, handled, and recovered from.
1// NullPointerException — using a null reference2String s = null;3s.length(); // → NullPointerException (we caused this; we can fix it)4
5// ClassNotFoundException — class not found at runtime6Class.forName("com.example.NonExistent"); // → ClassNotFoundExceptionError vs. Exception Comparison
| Feature | Error | Exception |
|---|---|---|
| Cause | JVM environment / system problem | Application code problem |
| Examples | OutOfMemoryError, StackOverflowError | NullPointerException, IOException |
| Can we handle? | ❌ Should not try | ✅ Yes, and we should |
| Type | Unchecked (runtime) | Checked or Unchecked |
| Hierarchy | Extends Error | Extends Exception |
5. Checked vs. Unchecked Exceptions
The Core Distinction
| Checked Exception | Unchecked Exception | |
|---|---|---|
| Also called | Compile-time exception | Runtime exception |
| When detected | At compile time | At runtime |
| Compiler forces handling? | ✅ Yes — code won't compile if unhandled | ❌ No — compiles fine |
| Hierarchy | Extends Exception (but not RuntimeException) | Extends RuntimeException |
| Examples | ClassNotFoundException, IOException, InterruptedException | NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException |
5.1 Unchecked (Runtime) Exceptions
Unchecked exceptions
are exceptions that occur during program execution. The compiler does not force you to handle them — your code compiles successfully even if they are present and unhandled.
Type 1: `ClassCastException`
Thrown when you try to cast an object to an incompatible type.
1public class Main {2 public static void main(String[] args) {3 Object val = Integer.valueOf(0); // val holds an Integer4 System.out.println((String) val); // trying to cast Integer → String5 }6}Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
Compiles fine → fails at runtime.
Type 2: `ArithmeticException`
Thrown when an illegal arithmetic operation occurs, most commonly division by zero.
1public class Main {2 public static void main(String[] args) {3 int result = 5 / 0; // division by zero4 System.out.println(result);5 }6}Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:3)Compiles fine → fails at runtime.
Type 3: `ArrayIndexOutOfBoundsException`
Thrown when you try to access an array element with an invalid index.
1public class Main {2 public static void main(String[] args) {3 int[] arr = new int[2]; // valid indices: 0, 14 System.out.println(arr[3]); // index 3 doesn't exist!5 }6}Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
Type 4: `StringIndexOutOfBoundsException`
Thrown when you try to access a character at an invalid position in a String.
1public class Main {2 public static void main(String[] args) {3 String val = "Hello"; // valid indices: 0, 1, 2, 3, 44 char c = val.charAt(5); // index 5 doesn't exist!5 }6}Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
Type 5: `NullPointerException`
Thrown when you try to use a reference that points to null — calling a method, accessing a field, or any other operation on it.
1public class Main {2 public static void main(String[] args) {3 String val = null;4 char c = val.charAt(0); // val is null — you're calling null.charAt(0)!5 }6}Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.charAt(int)" because "val" is null
Type 6: `NumberFormatException`
Thrown when you try to convert a String to a number but the String does not have a valid format.
1public class Main {2 public static void main(String[] args) {3 int num = Integer.parseInt("ABC"); // "ABC" is not a valid integer4 }5}Exception in thread "main" java.lang.NumberFormatException: For input string: "ABC"
1// This works fine:2int num = Integer.parseInt("53"); // → 535.2 Checked (Compile-Time) Exceptions
Checked exceptions
are exceptions that the compiler verifies at compile time. If your code might throw a checked exception and you haven't handled it, compilation fails.
Example: `ClassNotFoundException` (checked)
1public class Main {2 public static void main(String[] args) {3 method1();4 }5
6 static void method1() {7 throw new ClassNotFoundException("Class not found");8 // ❌ COMPILE ERROR:9 // unreported exception ClassNotFoundException; must be caught or declared to be thrown10 }11}The compiler refuses to compile this code. It demands that you either:
- Handle the exception with a
try-catchblock, OR - Declare that the method can throw it using
throws
Comparison: Runtime vs. Checked
1// ✅ COMPILES FINE — runtime exception, compiler doesn't care2static void method1() {3 throw new ArithmeticException("divide by zero");4}5
6// ❌ COMPILE ERROR — checked exception, compiler demands handling7static void method1() {8 throw new ClassNotFoundException("not found");9}6. Five Keywords of Exception Handling
Java provides exactly five keywords for exception handling:
| Keyword | Used With | Purpose |
|---|---|---|
try | Block of code | Wraps code that might throw an exception |
catch | Follows try | Catches and handles a specific exception type |
finally | Follows try or catch | Always executes — cleanup code |
throw | Inside a method | Manually throws an exception object |
throws | Method signature | Declares the exceptions a method might throw |
7. The `try-catch` Block
7.1 Basic try-catch
Syntax
1try {2 // Code that might throw an exception3 // If exception occurs here, control jumps to catch4} catch (ExceptionType exceptionObject) {5 // Handle the exception6 // exceptionObject contains type, message, stack trace7}8// Execution continues here after catch (if exception was handled)How It Works
Handling a Checked Exception with try-catch
1public class Main {2 public static void main(String[] args) {3 method1();4 }5
6 static void method1() {7 try {8 // Code that might throw ClassNotFoundException9 throw new ClassNotFoundException("Demo class not found");10 } catch (ClassNotFoundException e) {11 // Handle the exception — execution continues here12 System.out.println("Caught exception: " + e.getMessage());13 // You can: log it, set a default value, retry, etc.14 }15 System.out.println("Method1 continues after exception handling");16 }17}Caught exception: Demo class not found Method1 continues after exception handling
The program does not terminate. The exception is caught and handled, and execution resumes normally after the catch block.
Key Points
- Code inside
trythat comes after the line that throws the exception is skipped - Execution jumps directly to the matching
catchblock - After the
catchblock, execution continues normally after the entiretry-catchconstruct
1try {2 System.out.println("Line 1"); // ← executes3 throw new Exception("oops"); // ← exception thrown here4 System.out.println("Line 3"); // ← NEVER executes (skipped)5} catch (Exception e) {6 System.out.println("Caught: " + e.getMessage()); // ← executes7}8System.out.println("After try-catch"); // ← executesLine 1 Caught: oops After try-catch
7.2 Multiple catch Blocks
A single try block can be followed by multiple catch blocks, each handling a different exception type.
Syntax
1try {2 // code3} catch (ExceptionType1 e) {4 // handle ExceptionType15} catch (ExceptionType2 e) {6 // handle ExceptionType27} catch (ExceptionType3 e) {8 // handle ExceptionType39}Example
1public class Main {2 public static void main(String[] args) {3 method1();4 }5
6 // method1 declares it can throw two checked exceptions7 static void method1() throws ClassNotFoundException, InterruptedException {8 throw new ClassNotFoundException("Demo");9 }10}1// Handling in main with multiple catch blocks:2public static void main(String[] args) {3 try {4 method1();5 method2(); // might throw FileNotFoundException6 } catch (ClassNotFoundException e) {7 System.out.println("Class not found: " + e.getMessage());8 } catch (InterruptedException e) {9 System.out.println("Thread interrupted: " + e.getMessage());10 } catch (FileNotFoundException e) {11 System.out.println("File not found: " + e.getMessage());12 }13}catch block can only catch exceptions that could actually be thrown inside the corresponding try block. If you write a catch for an exception type that nothing in the try block can throw, you get a compile error.
``java
try {
method1(); // throws ClassNotFoundException only
} catch (FileNotFoundException e) { // ❌ COMPILE ERROR
// nobody throws FileNotFoundException in the try block!
}
``7.3 Catching Parent Exceptions Order Matters
Since Exception is the parent of all exceptions, a catch (Exception e) block can catch any exception. This has an important implication for ordering.
Rule: More Specific More General
Always place more specific catch blocks BEFORE more general ones.
1// ✅ CORRECT ORDER — specific first, general last2try {3 method1(); // throws ClassNotFoundException4} catch (ClassNotFoundException e) {5 System.out.println("Specific: Class not found");6} catch (Exception e) {7 System.out.println("General: Some other exception");8}1// ❌ WRONG ORDER — general first, specific second2try {3 method1();4} catch (Exception e) { // catches EVERYTHING5 System.out.println("General");6} catch (ClassNotFoundException e) { // ← COMPILE ERROR: already caught above7 System.out.println("Specific"); // unreachable!8}Why? If Exception is first, it catches every exception before the specific ones get a chance. Java detects this at compile time and throws an error saying the specific catch is "already caught."
7.4 Multiple Exceptions in One catch Block
Since Java 7, you can catch multiple exception types in a single catch block using the pipe | operator:
1try {2 method1(); // can throw ClassNotFoundException or InterruptedException3} catch (ClassNotFoundException | InterruptedException e) {4 // handles either one5 System.out.println("Caught: " + e.getMessage());6}This is cleaner when both exceptions are handled the same way, instead of:
1// Verbose — same body in both catch blocks2} catch (ClassNotFoundException e) {3 System.out.println("Caught: " + e.getMessage());4} catch (InterruptedException e) {5 System.out.println("Caught: " + e.getMessage()); // identical!6}You can also combine a multi-exception catch with a general catch:
1try {2 method1();3 method2();4} catch (ClassNotFoundException | InterruptedException e) {5 System.out.println("Specific handling: " + e.getMessage());6} catch (Exception e) {7 System.out.println("General fallback: " + e.getMessage());8}8. The `finally` Block
Definition
Thefinallyblock contains code that always executes regardless of whether an exception was thrown or caught — even if areturnstatement is executed insidetryorcatch.
Syntax Options
1// Option 1: try-catch-finally2try { } catch (Exception e) { } finally { }3
4// Option 2: try-finally (no catch)5try { } finally { }catch (multiple allowed), you can have at most one finally block per try.How finally Works
Example: finally Always Runs
1public class Main {2
3 static void method1() {4 try {5 System.out.println("Inside try");6 return; // ← returning from try block7 } finally {8 System.out.println("Inside finally"); // ← still executes!9 }10 }11
12 public static void main(String[] args) {13 method1();14 System.out.println("After method1");15 }16}Inside try Inside finally ← executed BEFORE the method actually returns After method1
Even though try has a return statement, finally executes before the method actually exits.
Example: finally with Exception
1static void method1() throws ClassNotFoundException {2 try {3 System.out.println("Before exception");4 throw new ClassNotFoundException("test");5 } catch (ClassNotFoundException e) {6 System.out.println("In catch: " + e.getMessage());7 } finally {8 System.out.println("In finally — always runs");9 }10}Before exception In catch: test In finally — always runs
try-finally Without catch (Delegating to Caller)
1// method1 has try-finally but NO catch — it still delegates the exception!2static void method1() throws ClassNotFoundException {3 try {4 throw new ClassNotFoundException("test");5 } finally {6 System.out.println("Finally executes, but exception still propagates");7 }8 // Exception propagates to caller — method1 doesn't handle it9}finally block is not a substitute for a catch block. If there is no catch, the exception still propagates to the caller — finally only ensures its code runs before the exception leaves the method.Primary Use Cases for finally
| Use Case | Why finally? |
|---|---|
| Closing file streams | File may remain open if exception occurs before close() |
| Releasing database connections | DB connections are limited; must always be released |
| Releasing locks | Deadlock occurs if a lock is never released |
| Logging | Ensure logging happens whether success or failure |
| Cleanup code | Any resource that must be freed regardless of outcome |
When finally Does NOT Execute
In the rare cases when finally is skipped:
- JVM-level errors —
OutOfMemoryError,StackOverflowError - System shutdown —
System.exit()called, process killed, power failure - Infinite loop in try/catch —
finallynever gets a turn
9. The `throw` Keyword
Definition
Thethrowkeyword is used to explicitly throw an exception from within code.
Usage 1: Throwing a New Exception
1// Syntax2throw new ExceptionType("message");1public class Main {2 static void validateName(String name) {3 if (name.equals("dummy")) {4 throw new IllegalArgumentException("Name cannot be 'dummy'");5 }6 System.out.println("Valid name: " + name);7 }8
9 public static void main(String[] args) {10 validateName("Alice"); // works fine11 validateName("dummy"); // throws exception12 }13}Valid name: Alice Exception in thread "main" java.lang.IllegalArgumentException: Name cannot be 'dummy'
Usage 2: Re-throwing a Caught Exception
You can catch an exception, do some processing (like logging), and then re-throw it for the caller to handle:
1public class Main {2 public static void main(String[] args) {3 try {4 method1();5 } catch (ClassNotFoundException e) {6 System.out.println("Main caught and handled: " + e.getMessage());7 }8 }9
10 static void method1() throws ClassNotFoundException {11 // method1 delegates to main12 throw new ClassNotFoundException("Class missing");13 }14}1// Re-throw pattern: catch, log, then throw again2static void method1() throws ClassNotFoundException {3 try {4 throw new ClassNotFoundException("original");5 } catch (ClassNotFoundException e) {6 System.out.println("Logging in method1: " + e.getMessage());7 throw e; // ← re-throw: let caller also handle it8 }9}When is re-throw useful? When you want to:
- Add logging or additional context at this level
- Transform the exception to a different type
- Perform partial cleanup, then let the caller do the rest
What Can You `throw`?
You can only throw objects that are instances of Throwable or any of its subclasses:
1throw new Exception("valid"); // ✅2throw new RuntimeException("valid"); // ✅3throw new ArithmeticException("valid"); // ✅4throw new Error("valid"); // ✅ (though you shouldn't)5throw new String("invalid"); // ❌ COMPILE ERROR — String is not Throwable6throw new Main(); // ❌ COMPILE ERROR — Main is not Throwable10. The `throws` Keyword
Definition
Thethrowskeyword is used in a method signature to declare that the method might throw one or more exceptions. It is a warning to the caller that they must handle or further propagate these exceptions.
Syntax
1accessModifier returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {2 // method body3}Example: Using `throws` to Delegate
1public class Main {2 public static void main(String[] args) throws ClassNotFoundException {3 // main delegates to its caller (JVM) — program will terminate if thrown4 method1();5 }6
7 static void method1() throws ClassNotFoundException {8 // method1 doesn't handle it — delegates to main9 throw new ClassNotFoundException("Class missing");10 }11}Chain of delegation:
1method1() throws → main() throws → JVM → program terminatesExample: `throws` Forcing the Caller to Handle
1static void method1() throws ClassNotFoundException, InterruptedException {2 // This method might throw either exception3}4
5// Caller MUST handle both, or re-declare throws:6public static void main(String[] args) {7 try {8 method1();9 } catch (ClassNotFoundException e) {10 System.out.println("Class not found");11 } catch (InterruptedException e) {12 System.out.println("Interrupted");13 }14}`throws` with Multiple Exceptions
1// Declare multiple exceptions using comma separation2static void method1() throws ClassNotFoundException, InterruptedException, IOException {3 // ...4}Key Point: `throws` is a Declaration, Not a Guarantee
throws says "this method might throw this exception." It does not mean it will always throw it. It is a compile-time contract that tells the caller to be prepared.11. `throw` vs. `throws` Complete Comparison
| Feature | throw | throws |
|---|---|---|
| Purpose | Actually throws an exception | Declares that a method may throw an exception |
| Where used | Inside a method body | In the method signature |
| Followed by | An exception object (instance) | An exception class name (type) |
| Number | Throws one exception at a time | Can declare multiple (comma-separated) |
| Example | throw new IOException("error"); | void m() throws IOException |
| Action | Immediately creates and throws | Just a warning/declaration |
1// throw — inside body, throws an INSTANCE2static void method1() throws ClassNotFoundException { // throws — in SIGNATURE, declares TYPE3 throw new ClassNotFoundException("not found"); // throw — in BODY, throws OBJECT4}12. Custom (User-Defined) Exceptions
Why Create Custom Exceptions?
Built-in exceptions are generic. Custom exceptions let you:
- Give domain-specific names (
InsufficientFundsException,InvalidAgeException) - Attach custom messages and data
- Make your code's intent clearer
How to Create a Custom Exception
Extend Exception (for checked) or RuntimeException (for unchecked):
1// Custom CHECKED exception (extends Exception)2public class MyCustomException extends Exception {3
4 // Constructor that accepts a message5 public MyCustomException(String message) {6 super(message); // pass message to parent Exception class7 }8}1// Custom UNCHECKED exception (extends RuntimeException)2public class MyCustomRuntimeException extends RuntimeException {3
4 public MyCustomRuntimeException(String message) {5 super(message);6 }7}Using a Custom Exception
1public class Main {2 public static void main(String[] args) {3 try {4 method1();5 } catch (MyCustomException e) {6 System.out.println("Custom exception caught: " + e.getMessage());7 }8 }9
10 static void method1() throws MyCustomException {11 // Some condition triggers the exception12 boolean someIssueArose = true;13 if (someIssueArose) {14 throw new MyCustomException("Some issue arose — custom message here");15 }16 }17}Custom exception caught: Some issue arose — custom message here
Custom Exception Hierarchy Where to Place It
1Throwable2└── Exception3 ├── RuntimeException4 │ └── MyCustomRuntimeException ← extends RuntimeException (unchecked)5 │6 └── MyCustomException ← extends Exception (checked)7 └── MyMoreSpecificException ← extends MyCustomExceptionYou can extend any class in the hierarchy:
- Extend
Exception→ your custom exception is checked - Extend
RuntimeException→ your custom exception is unchecked - Extend a specific exception → your custom exception inherits its behavior
Custom Exception with Extra Fields
1public class InsufficientFundsException extends Exception {2 private double amount; // how much was short3
4 public InsufficientFundsException(String message, double amount) {5 super(message);6 this.amount = amount;7 }8
9 public double getAmount() {10 return amount;11 }12}13
14// Usage15try {16 throw new InsufficientFundsException("Not enough funds", 150.00);17} catch (InsufficientFundsException e) {18 System.out.println(e.getMessage() + " | Short by: " + e.getAmount());19}20// Output: Not enough funds | Short by: 150.013. Handling Runtime Exceptions (Optional but Recommended)
Even though the compiler doesn't force you to handle runtime exceptions, it is often good practice to handle them:
1public class Main {2 public static void main(String[] args) {3 try {4 int result = 5 / 0; // ArithmeticException — runtime5 System.out.println(result);6 } catch (ArithmeticException e) {7 System.out.println("Cannot divide by zero: " + e.getMessage());8 // Set a default, retry, log — do something meaningful9 }10 System.out.println("Program continues normally");11 }12}Cannot divide by zero: / by zero Program continues normally
Without the try-catch, the program would terminate at the division. With it, the program recovers and continues.
14. Advantages of Exception Handling
1. Separates Error Handling from Regular Code
Without Exception Handling (Messy):
1// Everything mixed together — hard to read2static int processStudentClass(int classNumber) {3 if (classNumber > 0 && classNumber <= 12) {4 int numberOfStudents = getStudentCapacity(classNumber);5 if (numberOfStudents != 0) {6 String[] names = new String[numberOfStudents];7 if (names != null && names.length > 0) {8 names[0] = "New Value";9 return 0; // success10 } else {11 return -3; // error code 312 }13 } else {14 return -2; // error code 215 }16 } else {17 return -1; // error code 118 }19}With Exception Handling (Clean):
1// Regular code is clear; error handling is separated2static void processStudentClass(int classNumber) {3 try {4 int numberOfStudents = getStudentCapacity(classNumber);5 String[] names = new String[numberOfStudents];6 names[0] = "New Value";7 } catch (IllegalArgumentException e) {8 System.out.println("Invalid class number: " + e.getMessage());9 } catch (ArrayIndexOutOfBoundsException e) {10 System.out.println("Array error: " + e.getMessage());11 } catch (Exception e) {12 System.out.println("Unexpected error: " + e.getMessage());13 }14}The actual logic is clear. All error handling is in the catch blocks.
2. Eliminates Error Code Cascading
Without exception handling, errors must be propagated as return codes:
1// Without exception handling — error codes cascade2int code = method3(); // returns -1 on error3if (code == -1) {4 return -1; // method2 must pass it up5}6// method1 must also check and pass up...7// main must also check...With exception handling, exceptions propagate automatically:
1// With exception handling — automatic propagation2method3(); // throws exception if error3// method2, method1, main don't need to check return codes4// The exception travels up the stack on its own3. Allows Program Recovery
1try {2 // Attempt something risky3 connectToDatabase();4} catch (ConnectionException e) {5 // Recover: try a backup connection6 System.out.println("Primary DB failed, trying backup...");7 connectToBackupDatabase();8}9// Program continues running instead of crashing4. Aids Debugging with Stack Trace
The exception object provides:
- Type — what kind of problem
- Message — description of the problem
- Stack trace — exactly where it happened and how execution arrived there
5. Improves Security
You can catch exceptions and log only safe information, hiding sensitive data:
1catch (DatabaseException e) {2 // Don't log the full exception (might contain SQL, passwords, etc.)3 logger.error("Database error occurred for user: " + userId);4 // Don't expose: e.getMessage() (might contain sensitive query details)5}The One Disadvantage
15. When to Avoid Exception Handling
For simple, predictable conditions, use conditional logic instead of try-catch:
Avoid This (Expensive):
1static int divide(int a, int b) {2 try {3 return a / b;4 } catch (ArithmeticException e) {5 return -1; // b was zero6 }7}Prefer This (Simple and Cheap):
1static int divide(int a, int b) {2 if (b == 0) {3 return -1; // handle directly4 }5 return a / b;6}The second version is:
- Faster (no exception object created)
- Clearer in intent
- Avoids unnecessary JVM overhead
if-else for expected, predictable conditions.16. Common Runtime Exceptions Reference
| Exception | Common Cause | Example |
|---|---|---|
NullPointerException | Using a null reference | null.length() |
ArithmeticException | Illegal arithmetic | 5 / 0 |
ArrayIndexOutOfBoundsException | Invalid array index | arr[arr.length] |
StringIndexOutOfBoundsException | Invalid string position | "hello".charAt(10) |
ClassCastException | Invalid type cast | (String) integerObj |
NumberFormatException | Invalid string-to-number | Integer.parseInt("abc") |
StackOverflowError | Infinite recursion | Recursive call with no base case |
OutOfMemoryError | Heap exhausted | Creating too many/large objects |
IllegalArgumentException | Invalid method argument | Passing negative to sqrt() |
IllegalStateException | Method called at wrong time | Iterator modified during iteration |
17. Summary Diagrams
Complete Exception Hierarchy
Five Keywords Decision Flow
18. Common Mistakes
Mistake 1: Catching a More General Exception Before a Specific One
1// ❌ WRONG — Exception catches everything; ClassNotFoundException unreachable2try { method1(); }3catch (Exception e) { }4catch (ClassNotFoundException e) { } // COMPILE ERROR5
6// ✅ CORRECT — specific first, general last7try { method1(); }8catch (ClassNotFoundException e) { }9catch (Exception e) { }Mistake 2: Catching an Exception That Can't Be Thrown
1static void method1() throws ClassNotFoundException { }2
3try {4 method1();5} catch (FileNotFoundException e) { } // ❌ COMPILE ERROR6// method1 can only throw ClassNotFoundException, not FileNotFoundExceptionMistake 3: Empty catch Blocks (Swallowing Exceptions)
1// ❌ BAD — silently swallows the exception, hides the problem2try {3 riskyOperation();4} catch (Exception e) {5 // nothing here6}7
8// ✅ GOOD — at minimum, log the exception9try {10 riskyOperation();11} catch (Exception e) {12 e.printStackTrace(); // or use a proper logger13}Mistake 4: Using `throws` Instead of `throw` (and Vice Versa)
1// ❌ WRONG — throw is for objects, not type names2throw ClassNotFoundException;3
4// ❌ WRONG — throws is for signatures, not inside body5void method() {6 throws new ClassNotFoundException();7}8
9// ✅ CORRECT10void method() throws ClassNotFoundException {11 throw new ClassNotFoundException("message");12}Mistake 5: Forgetting `finally` Still Runs After `return`
1try {2 return 1; // ← you might think the method returns 1 here3} finally {4 return 2; // ← WRONG: finally runs and overrides the return value!5}6// Method returns 2, not 1!return inside a finally block. It overrides any return value from try or catch, which is confusing and error-prone.Mistake 6: Using Exception Handling for Normal Control Flow
1// ❌ BAD — using exception for expected condition2try {3 int[] arr = new int[5];4 int i = 0;5 while (true) {6 process(arr[i++]); // expects ArrayIndexOutOfBoundsException to stop the loop7 }8} catch (ArrayIndexOutOfBoundsException e) {9 // done10}11
12// ✅ GOOD — use normal conditional logic13int[] arr = new int[5];14for (int i = 0; i < arr.length; i++) {15 process(arr[i]);16}19. Best Practices
- Always handle specific exceptions — catch
ClassNotFoundExceptionrather thanExceptionwherever possible. Generic catches hide problems. - Never swallow exceptions — at minimum, log the exception. Silent catch blocks are production bugs waiting to happen.
- Use
finallyfor resource cleanup — or better yet, use try-with-resources (Java 7+) forCloseableresources. - Handle exceptions as early as possible — the closer to the source, the smaller the stack trace and the lower the overhead.
- Use custom exceptions for domain logic —
InvalidAgeExceptioncommunicates intent far better thanIllegalArgumentException. - Don't use exceptions for flow control — exceptions are expensive; use
if-elsefor expected conditions. - Order catch blocks from specific to general — most specific first,
Exceptionlast as a catch-all. - Include meaningful messages —
throw new IOException("Failed to read config.properties")is better thanthrow new IOException(). - Re-throw with context when needed — add logging or context before re-throwing so debugging is easier.
- Avoid
returninfinally— it suppresses exceptions and return values in confusing ways.
20. Interview Notes
Commonly Asked Questions
Q1: What is an exception in Java?
Answer: An exception is an event that occurs during program execution that disrupts the normal flow of instructions. When it occurs, the runtime creates an exception object containing the type, message, and stack trace, and searches the call stack for a handler.
Q2: What is the difference between `Error` and `Exception`?
Answer: Error represents serious JVM-level problems (out of memory, stack overflow) that are outside the application's control and should not be handled. Exception represents problems in application code that can be anticipated and handled. Both extend Throwable.
Q3: What is the difference between checked and unchecked exceptions?
Answer:
- Checked (compile-time) — compiler forces you to handle or declare them. Code won't compile if unhandled. Examples:
ClassNotFoundException,IOException. - Unchecked (runtime) — compiler does not force handling. Code compiles fine; exception occurs at runtime. Examples:
NullPointerException,ArithmeticException.
Q4: What is the difference between `throw` and `throws`?
Answer:
throw— used inside a method body to manually throw an exception instance:throw new IOException()throws— used in method signature to declare that the method might throw an exception:void m() throws IOException
Q5: What is the `finally` block? When is it NOT executed?
Answer: finally always executes after try and any catch block, regardless of whether an exception was thrown or a return statement was executed. It is not executed when: a JVM-level Error occurs, System.exit() is called, or the process is forcefully killed.
Q6: Can you have a `try` without `catch`?
Answer: Yes. try-finally is valid (no catch). However, the exception still propagates — finally just ensures cleanup code runs. You can also have try-catch-finally or just try-catch.
Q7: What is a stack trace?
Answer: A stack trace is the chain of method calls from where an exception occurred back to the entry point (main()). It shows the exception type, message, and each method name, class name, and line number in the call chain. It is the primary debugging tool for exceptions.
Q8: Can we catch multiple exceptions in one `catch` block?
Answer: Yes, since Java 7: catch (ClassNotFoundException | InterruptedException e) { }. Useful when the handling logic is identical for multiple exception types.
Q9: When would you create a custom exception?
Answer: When the built-in exception types don't convey enough domain-specific meaning. For example, InsufficientFundsException is far clearer than IllegalArgumentException in a banking context. Custom exceptions can also carry additional fields (like the amount that was short).
Q10: What is the disadvantage of exception handling?
Answer: Exception handling is expensive when exceptions propagate through a large call stack. JVM must traverse the stack looking for a handler. If exceptions are not handled near their source, the overhead increases. It should not be used for expected control flow — use if-else for predictable conditions.
Q11: Is `Error` checked or unchecked?
Answer: Unchecked. Errors are runtime events (they occur when JVM runs out of memory or the stack overflows). The compiler does not force you to handle them.
Q12: What happens if an exception is never caught?
Answer: The exception propagates up the call stack. If no method handles it, the JVM terminates the program abruptly and prints the stack trace to the console.
21. Practice Questions
Easy
- What is an exception? What disrupts the "normal flow"?
- What three pieces of information does an exception object contain?
- What is the difference between
ErrorandException? - Name three checked exceptions and three unchecked exceptions.
- What is the difference between
throwandthrows? - Is
finallyblock guaranteed to always execute? Give a case where it doesn't. - Can a
tryblock exist without acatchblock? Without afinallyblock?
Medium
- Write a method that throws a
ClassNotFoundException. Write two versions of a caller — one usingthrows, one usingtry-catch. - Explain why catch blocks must be ordered from most specific to most general. What compile error do you get if they are reversed?
- What is the difference between runtime and compile-time exceptions? Give two examples of each and show code that demonstrates how the compiler treats them differently.
- Write a
try-catch-finallyblock and trace through it for two cases: (a) no exception thrown, (b) exception thrown and caught. - Create a custom checked exception
InvalidAgeExceptionand use it in a method that validates a person's age (must be between 0 and 150). - Explain with code how re-throwing works. When would you use it?
- What is the output of this code? Explain why.
1 try {2 System.out.println("try");3 return;4 } finally {5 System.out.println("finally");6 }Hard
- Write a program that demonstrates ALL five exception keywords (
try,catch,finally,throw,throws) in a realistic scenario (e.g., a file reader). - Explain the call-stack propagation of an exception through five nested method calls. At what point should you handle the exception, and why?
- Why is exception handling considered "expensive"? What specifically makes it costly when the stack trace is long? How would you measure this cost?
- Rewrite this code to avoid exception handling and explain why your version is preferable:
1 static int divide(int a, int b) {2 try { return a / b; }3 catch (ArithmeticException e) { return -1; }4 }- What is the difference between catching
Exceptionand catchingThrowable? When would each be appropriate? - Design a complete exception hierarchy for a banking application with at minimum: a base
BankingException,InsufficientFundsException,AccountNotFoundException, andDailyLimitExceededException. Show how they would be used in atransfer()method.
22. Quick Revision Summary
1☕ JAVA EXCEPTION HANDLING — KEY POINTS2
3📌 WHAT IS AN EXCEPTION:4 Event during execution that disrupts normal flow5 Creates exception object with: type + message + stack trace6 JVM searches call stack for a handler; if none → program terminates7
8🏗️ HIERARCHY:9 Object → Throwable → Error (don't handle)10 → Exception (handle these)11 → RuntimeException (UNCHECKED)12 → Other exceptions (CHECKED)13
14⚡ ERROR vs EXCEPTION:15 Error → JVM problems (OutOfMemory, StackOverflow)16 Should NOT be handled17 Unchecked (runtime)18 Exception → Application problems19 Should be handled20 Checked or Unchecked21
22🔍 CHECKED vs UNCHECKED:23 Checked (Compile-time):24 → Compiler FORCES you to handle25 → Code won't compile if unhandled26 → Examples: ClassNotFoundException, IOException, InterruptedException27 28 Unchecked (Runtime):29 → Compiler does NOT force handling30 → Code compiles; exception occurs at runtime31 → Examples: NullPointerException, ArithmeticException,32 ArrayIndexOutOfBoundsException, ClassCastException,33 NumberFormatException34
35🔑 FIVE KEYWORDS:36 try → wraps risky code37 catch → handles specific exception type (can have multiple)38 finally → ALWAYS executes (cleanup); only one allowed39 throw → inside method body; throws an exception OBJECT40 throws → in method SIGNATURE; declares exception TYPE that may be thrown41
42📋 try-catch RULES:43 • catch only what can be thrown in the try block44 • Order: SPECIFIC → GENERAL (specific catch first)45 • Multiple catch blocks allowed46 • Multi-exception catch: catch(TypeA | TypeB e) since Java 747
48🧹 finally RULES:49 • Always executes after try/catch (even after return)50 • Only ONE finally block per try51 • NOT executed if: JVM Error, System.exit(), process killed52 • Use for: closing streams, releasing locks, cleanup53
54🎯 throw vs throws:55 throw → throws an INSTANCE: throw new IOException()56 throws → declares a TYPE: void m() throws IOException57
58🛠️ CUSTOM EXCEPTIONS:59 Extend Exception → checked exception60 Extend RuntimeException → unchecked exception61 Call super(message) in constructor62
63✅ ADVANTAGES:64 • Separates error handling from regular code (clean code)65 • Eliminates error code cascading66 • Allows recovery from errors67 • Stack trace aids debugging68 • Can hide sensitive information in logs69
70⚠️ DISADVANTAGES:71 • Expensive if stack trace is large and exception not handled early72 • Don't use for predictable, expected conditions73
74🚫 AVOID EXCEPTION HANDLING WHEN:75 Simple if-else can handle the condition76 Use: if (b == 0) return -1;77 Not: try { a/b } catch (ArithmeticException e) { return -1; }78
79⚠️ KEY INTERVIEW POINTS:80 • Error = unchecked (not our problem to handle)81 • Checked = compile-time = MUST handle or declare82 • Unchecked = runtime = compiler won't force you83 • finally always runs (except JVM crash/System.exit)84 • throw (object) vs throws (declaration in signature)85 • Catch order: specific first, general (Exception) last86 • Exception handling is expensive — don't overuseEnd of Chapter — Exception Handling in Java
FileReader, BufferedReader, streams, try-with-resources
- Multithreading — Thread, Runnable, synchronization, InterruptedException handling
- Collections Framework — ArrayList, HashMap and how they throw exceptions like ConcurrentModificationExceptionStudy Guide generated from: Java Basics to Advanced — Exception Handling
Practice & Implement
Apply what you learned in Exception Handling
Create `PaymentException` and `InsufficientFundsException extends PaymentException`. Write `processPayment(amount, balance)` — throws appropriate exception. Catch specifically and print messages.
Funds error: Need 500.0 but only have 200.0 Payment error: Amount must be positive
Mastery check
How well can you recall this?
Finished this lesson?