Skip to main content
Java Basics
CHAPTER 19 Beginner

Exception Handling

Updated: May 17, 2026
5 min read

# CHAPTER 19

Exception Handling

1. Introduction

Exceptions are unexpected events that disrupt normal program flow — dividing by zero, opening a missing file, or accessing an invalid array index. Without handling them, your program crashes. Exception handling lets you anticipate errors and respond gracefully.

2. The Exception Hierarchy

123456789101112
Throwable
├── Error (JVM issues — don't catch these)
│   ├── OutOfMemoryError
│   └── StackOverflowError
└── Exception
    ├── IOException (Checked)
    ├── SQLException (Checked)
    └── RuntimeException (Unchecked)
        ├── NullPointerException
        ├── ArrayIndexOutOfBoundsException
        ├── ArithmeticException
        └── ClassCastException

3. try-catch Block

java
123456
try {
    int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Error: Cannot divide by zero!");
    System.out.println("Details: " + e.getMessage());
}

4. Multiple catch Blocks

java
12345678910
try {
    int[] arr = {1, 2, 3};
    System.out.println(arr[10]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
    System.out.println("Math error");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index error");
} catch (Exception e) {
    System.out.println("General error: " + e.getMessage());
}

5. The finally Block

Always executes, whether an exception occurs or not — used for cleanup (closing files, connections).
java
1234567
try {
    // risky code
} catch (Exception e) {
    // handle error
} finally {
    System.out.println("This ALWAYS runs.");
}

6. throw and throws

  • throw: Manually throw an exception.
  • throws: Declare that a method might throw an exception.
java
12345
public static void validateAge(int age) throws IllegalArgumentException {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative!");
    }
}

7. Checked vs Unchecked Exceptions

TypeWhenExample
CheckedMust handle at compile timeIOException, SQLException
UncheckedRuntime errorsNullPointerException, ArithmeticException

8. Custom Exceptions

java
123456789101112131415
class InsufficientFundsException extends Exception {
    private double amount;
    public InsufficientFundsException(double amount) {
        super("Insufficient funds. Short by: $" + amount);
        this.amount = amount;
    }
}

// Usage
public void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException(amount - balance);
    }
    balance -= amount;
}

9. try-with-resources (Java 7+)

Automatically closes resources:
java
123
try (Scanner sc = new Scanner(System.in)) {
    String input = sc.nextLine();
} // Scanner automatically closed here

10. Mini Project: Safe Division Calculator

java
12345678910111213141516171819202122
import java.util.Scanner;
import java.util.InputMismatchException;

public class SafeCalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            System.out.print("Enter numerator: ");
            int a = sc.nextInt();
            System.out.print("Enter denominator: ");
            int b = sc.nextInt();
            System.out.println("Result: " + (a / b));
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
        } catch (InputMismatchException e) {
            System.out.println("Error: Please enter valid integers!");
        } finally {
            System.out.println("Calculator session ended.");
            sc.close();
        }
    }
}

11. MCQ Quiz with Answers

Question 1

Which block always executes?

Question 2

Checked exceptions must be:

Question 3

NullPointerException is:

Question 4

throw is used to:

Question 5

Custom exceptions extend:

Question 6

try-with-resources automatically:

Question 7

Which is NOT an unchecked exception?

Question 8

throws is used in:

Question 9

What does e.getMessage() return?

Question 10

Can catch blocks be chained?

12. Interview Questions

  • Q: Difference between throw and throws?
  • Q: Difference between checked and unchecked exceptions?
  • Q: What is the purpose of finally?
  • Q: When would you create a custom exception?

13. Summary

Exception handling prevents crashes by catching errors gracefully. Use try-catch-finally for structured handling. throw creates exceptions; throws declares them. Custom exceptions improve error communication. try-with-resources auto-closes resources.

14. Next Chapter Recommendation

In Chapter 20: Collections Framework, we'll explore Java's powerful data structure library — ArrayList, HashMap, HashSet, and more.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·