Back to Java Programming
Java Programming

Exception Handling

try-catch-finally, custom exceptions, checked vs unchecked exceptions, and best practices.

BeginnerIntermediateAdvanced

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?
Answer: Checked exceptions (e.g., IOException, ClassNotFoundException) are checked at compile time — must be caught or declared with `throws`. Unchecked exceptions (e.g., NullPointerException, ArithmeticException) extend RuntimeException and are not mandatorily handled.
Q2.What is the role of the `finally` block?
Answer: `finally` always executes whether or not an exception occurs (except System.exit()). It is used to release resources like closing files, database connections, or streams.
Q3.Can we have multiple catch blocks? What is the order?
Answer: Yes. Multiple catch blocks are allowed. They must be ordered from most specific to most general — a child class exception should appear before the parent class exception. Otherwise, a compile-time error occurs.
Q4.What is the difference between `throw` and `throws`?
Answer: `throw` is used inside a method to explicitly throw an exception object: `throw new NullPointerException()`. `throws` is used in a method signature to declare that it may throw checked exceptions: `void read() throws IOException`.
Q5.What happens if an exception is thrown in a finally block?
Answer: If an exception is thrown in finally, it overrides/suppresses the original exception from the try/catch block. The original exception is lost unless stored via `Throwable.addSuppressed()`.
Q6.How do you create a custom exception?
Answer: Extend `Exception` for checked: `class MyException extends Exception { MyException(String msg) { super(msg); } }`. Extend `RuntimeException` for unchecked. Throw with `throw new MyException("message")`.

🔘 MCQ Practice — Exception Handling

MCQ 1.Which exception is thrown when dividing an integer by zero in Java?
A. NullPointerException
B. NumberFormatException
C. ArithmeticException
D. IllegalArgumentException

✓ Correct Answer: ArithmeticException

MCQ 2.What is the parent class of all exceptions in Java?
A. Exception
B. Error
C. Throwable
D. RuntimeException

✓ Correct Answer: Throwable

MCQ 3.Which block always executes regardless of whether an exception was thrown?
A. try
B. catch
C. finally
D. throws

✓ 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.

More Java Programming Topics

Related Subjects

Frequently Asked Questions — Exception Handling

What is Exception Handling in Java Programming?
Exception handling in Java is a mechanism using try-catch-finally and throws/throw to handle runtime errors gracefully without crashing the program.
What is the difference between checked and unchecked exceptions?
Checked exceptions (e.g., IOException, ClassNotFoundException) are checked at compile time — must be caught or declared with `throws`. Unchecked exceptions (e.g., NullPointerException, ArithmeticException) extend RuntimeException and are not mandatorily handled.
What is the role of the `finally` block?
`finally` always executes whether or not an exception occurs (except System.exit()). It is used to release resources like closing files, database connections, or streams.
Can we have multiple catch blocks? What is the order?
Yes. Multiple catch blocks are allowed. They must be ordered from most specific to most general — a child class exception should appear before the parent class exception. Otherwise, a compile-time error occurs.
What is the difference between `throw` and `throws`?
`throw` is used inside a method to explicitly throw an exception object: `throw new NullPointerException()`. `throws` is used in a method signature to declare that it may throw checked exceptions: `void read() throws IOException`.
What happens if an exception is thrown in a finally block?
If an exception is thrown in finally, it overrides/suppresses the original exception from the try/catch block. The original exception is lost unless stored via `Throwable.addSuppressed()`.
How do I prepare Exception Handling for exams?
To master Exception Handling, start by reading the theory carefully, then go through solved examples step by step. Practice numericals (if applicable), revise key formulas, and attempt previous year questions. SII notes cover all these aspects in a structured manner.
Are these Exception Handling notes free?
Yes! SII provides free access to Exception Handling notes and introductory study materials. Enrolled students get full access to detailed notes, solved papers, and live doubt-clearing sessions.
Which exams ask questions from Exception Handling?
Exception Handling is an important topic tested in Beginner, Intermediate, Advanced board exams, as well as GATE (CS & IT), University Semester Exams. It frequently appears in both short-answer and long-answer sections.