Exception Handling
try-catch-finally, custom exceptions, checked vs unchecked exceptions, and best practices.
What You Will Learn in Exception Handling
Exception handling in Java is a mechanism using try-catch-finally and throws/throw to handle runtime errors gracefully without crashing the program.
- Exception hierarchy: Throwable → Error (JVM errors) | Exception → RuntimeException (unchecked) | Checked exceptions.
- try block encloses risky code; catch block handles specific exception types; finally always executes.
- Checked exceptions (IOException, SQLException) must be declared with `throws` or caught.
- Unchecked exceptions (NullPointerException, ArrayIndexOutOfBoundsException) extend RuntimeException.
- `throw` manually throws an exception; `throws` declares that a method may throw exceptions.
- Custom exceptions: extend Exception (checked) or RuntimeException (unchecked).
Syntax
try {
// risky code
} catch (SpecificException e) {
// handle specific exception
} catch (Exception e) {
// handle any other exception
} finally {
// always runs (e.g., close resources)
}Complete Code Example
import java.io.*;
public class ExceptionDemo {
// Custom exception
static class InsufficientFundsException extends Exception {
InsufficientFundsException(double amount) {
super("Insufficient funds. Required: " + amount);
}
}
static void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) throw new InsufficientFundsException(amount);
System.out.println("Withdrawn: " + amount);
}
public static void main(String[] args) {
try {
withdraw(500, 1000);
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Transaction complete.");
}
}
}
// Output:
// Error: Insufficient funds. Required: 1000.0
// Transaction complete.Example
`try { int x = 10/0; } catch(ArithmeticException e) { ... }` catches division-by-zero without crashing.
Expected Exam Questions — Exception Handling
Q1.What is the difference between checked and unchecked exceptions?
Q2.What is the role of the `finally` block?
Q3.Can we have multiple catch blocks? What is the order?
Q4.What is the difference between `throw` and `throws`?
Q5.What happens if an exception is thrown in a finally block?
Q6.How do you create a custom exception?
🔘 MCQ Practice — Exception Handling
MCQ 1.Which exception is thrown when dividing an integer by zero in Java?
✓ Correct Answer: ArithmeticException
MCQ 2.What is the parent class of all exceptions in Java?
✓ Correct Answer: Throwable
MCQ 3.Which block always executes regardless of whether an exception was thrown?
✓ Correct Answer: finally
Download Exception Handling PDF Notes
Get the complete Exception Handling notes as a PDF — free for enrolled students, or browse our public study materials library.