Skip to main content

Advanced Java

Exception Handling

Complete lesson for Exception Handling using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Exception Handling

Section: Advanced Java. Handle problems without crashing: exception hierarchy, checked vs unchecked, try, catch, finally, throw, throws, custom exceptions, and try-with-resources — with small real-life examples.

What is an exception?

  • An exception is an unwanted event that happens while the program runs and disturbs the normal flow of instructions.
  • In Java an exception is an object of a class that extends Throwable. It carries the type of problem, a message, and the call stack.
  • Exception handling means catching that object and responding, so the program can continue instead of terminating abruptly.
  • Real life: you are driving to the office and get a flat tyre (the exception). You change to the spare tyre (handling it) and continue the journey. Without a spare, the journey ends there (program crash).
TermMeaningReal-life comparison
ExceptionA problem the program can catch and recover fromFlat tyre on the way to office
Exception handlingCode that responds to the problemUsing the spare tyre
ErrorA serious JVM or system problem, usually not recoverableThe road is washed away by a flood
Stack traceThe list of method calls active when the exception happenedThe route map showing where you broke down
Unhandled exceptionNo matching catch, so the thread stopsNo spare tyre: the trip is cancelled
public class BillSplitter {
    public static void main(String[] args) {
        int bill = 1200;
        int friends = 0;                         // nobody came!

        // Without handling, this line would crash the program:
        // System.out.println(bill / friends);   // ArithmeticException: / by zero

        try {
            System.out.println("Each pays: " + bill / friends);
        } catch (ArithmeticException e) {
            System.out.println("Cannot split a bill among 0 friends");
        }
        System.out.println("Program continues normally");
    }
}

Real-life examples of common exceptions

  • Each common exception has an everyday meaning. Remembering the real-life picture makes the cause easy to spot.
ExceptionSmall real-life exampleJava code that causes itType
ArithmeticExceptionSplitting a Rs.1200 bill among 0 friendsint share = 1200 / friends; with friends = 0Unchecked
NullPointerExceptionCalling a contact whose phone number is emptyString phone = null; phone.length();Unchecked
ArrayIndexOutOfBoundsExceptionAsking for seat 51 in a 50-seat busint[] seats = new int[50]; seats[50] = 1;Unchecked
StringIndexOutOfBoundsExceptionReading the 10th letter of the word "Java""Java".charAt(10);Unchecked
NumberFormatExceptionTyping "twenty" in an age box that expects digitsInteger.parseInt("twenty");Unchecked
ClassCastExceptionTreating a dog as if it were a catObject o = "hi"; Integer i = (Integer) o;Unchecked
IllegalArgumentExceptionOrdering -3 pizzasthrow new IllegalArgumentException("qty must be at least 1");Unchecked
InputMismatchExceptionEntering letters when the form asks for a PINnew Scanner("abc").nextInt();Unchecked
FileNotFoundExceptionOpening a document that was deletednew FileReader("missing.txt");Checked
IOExceptionInternet cut while downloading a fileReading from a broken network streamChecked
SQLExceptionThe bank database server is downDriverManager.getConnection(url) failsChecked
InterruptedExceptionSomeone wakes you up while you are sleepingThread.sleep(1000) is interruptedChecked
OutOfMemoryErrorPouring 2 litres of water into a 1-litre bottleAdding objects to a list foreverError
StackOverflowErrorTwo mirrors facing each other: endless reflectionsA recursive method with no base caseError
public class CommonExceptions {
    public static void main(String[] args) {
        Runnable[] mistakes = {
            () -> { int friends = 0; System.out.println(1200 / friends); },
            () -> { String phone = null; System.out.println(phone.length()); },
            () -> { int[] seats = new int[50]; seats[50] = 1; },
            () -> { System.out.println("Java".charAt(10)); },
            () -> { System.out.println(Integer.parseInt("twenty")); },
            () -> { Object o = "hi"; Integer i = (Integer) o; System.out.println(i); }
        };
        for (Runnable r : mistakes) {
            try {
                r.run();
            } catch (RuntimeException e) {
                System.out.println("Caught " + e.getClass().getSimpleName());
            }
        }
        System.out.println("All mistakes handled, program still running");
    }
}

Exception hierarchy

  • Throwable is the root of everything that can be thrown or caught. It has two direct children: Error and Exception.
  • Error: serious JVM problems such as OutOfMemoryError and StackOverflowError. Do not catch them in normal code.
  • Exception: problems a program may want to handle. Its subclasses (except RuntimeException) are checked exceptions.
  • RuntimeException and its subclasses are unchecked exceptions, usually caused by programming mistakes.
  • A catch block for a parent type also catches all its children: catch (Exception e) catches IOException and NullPointerException.
ClassDirect parentTypeThrown when
ThrowableObjectRootSuperclass of every exception and error
ErrorThrowableErrorSerious JVM or system problem
OutOfMemoryErrorVirtualMachineErrorErrorThe heap is full
StackOverflowErrorVirtualMachineErrorErrorRecursion goes too deep
ExceptionThrowableCheckedConditions a program may want to catch
IOExceptionExceptionCheckedInput or output fails
FileNotFoundExceptionIOExceptionCheckedA file cannot be opened
SQLExceptionExceptionCheckedDatabase access fails
ClassNotFoundExceptionReflectiveOperationExceptionCheckedA class cannot be found by name at runtime
InterruptedExceptionExceptionCheckedA sleeping or waiting thread is interrupted
RuntimeExceptionExceptionUncheckedParent of programming-error exceptions
ArithmeticExceptionRuntimeExceptionUncheckedInteger division by zero
NullPointerExceptionRuntimeExceptionUncheckedUsing a null reference
ArrayIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionUncheckedInvalid array index
NumberFormatExceptionIllegalArgumentExceptionUncheckedText is not a valid number
ClassCastExceptionRuntimeExceptionUncheckedInvalid type cast

Java exception hierarchy — Error, checked, and unchecked

Everything that can be thrown is a Throwable. Errors (red) are serious JVM problems. Checked exceptions (orange) must be caught or declared with throws. Unchecked exceptions (green) extend RuntimeException and usually mean a bug in the code.

Java exception hierarchy tree: Object, then Throwable, which splits into Error (OutOfMemoryError, StackOverflowError) and Exception. Under Exception are checked exceptions IOException, InterruptedException, ClassNotFoundException, FileNotFoundException, NoSuchMethodException, and RuntimeException with unchecked exceptions NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException, StringIndexOutOfBoundsException.
Java exception hierarchy — grouped by kind; see the table below for each exact parent class
  • Error: OutOfMemoryError, StackOverflowError — do not catch in normal code.
  • Checked: IOException, SQLException, InterruptedException — compiler forces catch or throws.
  • Unchecked: NullPointerException, ArithmeticException, NumberFormatException — prevent with checks.
  • Catching a parent also catches its children, so write child catch blocks first.

Differences between checked exceptions, unchecked exceptions, and errors

PointChecked exceptionUnchecked exceptionError
SuperclassException (but not RuntimeException)RuntimeExceptionError
Checked by the compiler?Yes: must catch or declare with throwsNoNo
When it happensAt runtime, but the compiler forces you to plan for itAt runtimeAt runtime
Usual causeThings outside the program: files, network, databaseProgramming mistakes: null, bad index, bad castJVM or system failure
Recoverable?Usually: retry, ask for another fileFix the codeUsually not
ExamplesIOException, SQLException, InterruptedExceptionNullPointerException, ArithmeticException, ArrayIndexOutOfBoundsExceptionOutOfMemoryError, StackOverflowError
Real lifeThe train may be late, so plan a backupForgetting your ticket: your own mistakeAn earthquake: nothing you can do
Should you catch it?Yes, or declare itPrevent with checks; catch at boundariesNo

What happens when an exception is not handled

  • The JVM creates the exception object and looks for a matching catch block in the current method, then in the caller, and so on up the call stack.
  • If no method catches it, the default exception handler prints the exception type, message, and stack trace, and the thread terminates.
  • Statements after the failing line never run.
public class NoHandling {
    static int divide(int a, int b) {
        return a / b;
    }

    public static void main(String[] args) {
        System.out.println("Start");
        System.out.println(divide(10, 0));   // crashes here
        System.out.println("End");           // never printed
    }
}
// Output:
// Start
// Exception in thread "main" java.lang.ArithmeticException: / by zero
//     at NoHandling.divide(NoHandling.java:3)
//     at NoHandling.main(NoHandling.java:8)

try and catch

  • Put risky statements inside try. If an exception happens, Java jumps to the matching catch block and skips the rest of try.
  • The catch parameter (e) is the exception object. Use e.getMessage() for details.
  • After the catch block finishes, the program continues with the next statement after the try-catch.
  • Real life: a safety net under a trapeze artist. The show goes on even if the artist slips.
public class AgeInput {
    public static void main(String[] args) {
        String[] inputs = { "25", "twenty", "40" };
        for (String text : inputs) {
            try {
                int age = Integer.parseInt(text);   // may throw
                System.out.println("Age accepted: " + age);
            } catch (NumberFormatException e) {
                System.out.println("'" + text + "' is not a number. Please type digits.");
            }
        }
        System.out.println("Form closed");
    }
}

Multiple catch blocks and multi-catch

  • One try can have many catch blocks. Java checks them top to bottom and runs only the first match.
  • Order them from specific to general. A parent type above its child is a compile error: exception has already been caught.
  • Multi-catch (Java 7) handles several unrelated types in one block: catch (NumberFormatException | ArithmeticException e). The types must not be parent and child.
  • Real life: a hospital sends a broken arm to orthopaedics and a fever to general medicine; anything unusual goes to the general emergency desk last.
public class TicketCounter {
    public static void main(String[] args) {
        int[] fares = { 500, 750, 1200 };                // fare for routes 0, 1, 2
        String[][] orders = { {"1", "2"}, {"5", "1"}, {"x", "1"}, {"2", "0"} };

        for (String[] o : orders) {
            try {
                int route = Integer.parseInt(o[0]);      // NumberFormatException
                int people = Integer.parseInt(o[1]);
                int total = fares[route];                // ArrayIndexOutOfBoundsException
                System.out.println("Each of " + people + " pays " + total / people); // ArithmeticException
            } catch (NumberFormatException e) {
                System.out.println("Route must be a number");
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("No such route: " + o[0]);
            } catch (ArithmeticException e) {
                System.out.println("People cannot be zero");
            } catch (Exception e) {                      // most general type always LAST
                System.out.println("Unexpected: " + e);
            }
        }
    }
}
// Output:
// Each of 2 pays 375
// No such route: 5
// Route must be a number
// People cannot be zero

finally block

  • finally runs whether the try block succeeds, an exception is caught, or an exception escapes. It even runs after return.
  • Use it for cleanup: closing files, releasing locks, printing a summary.
  • It does not run if the JVM stops, for example with System.exit() or a power failure.
  • Real life: you turn off the gas stove after cooking, whether the dish came out perfect or burnt.
public class Cooking {
    static String cook(boolean burnt) {
        System.out.println("Gas stove ON");
        try {
            if (burnt) {
                throw new IllegalStateException("Dish burnt!");
            }
            return "Dish ready";
        } catch (IllegalStateException e) {
            return "Order food online (" + e.getMessage() + ")";
        } finally {
            System.out.println("Gas stove OFF");   // always runs, even after return
        }
    }

    public static void main(String[] args) {
        System.out.println(cook(false));
        System.out.println("---");
        System.out.println(cook(true));
    }
}
// Output:
// Gas stove ON
// Gas stove OFF
// Dish ready
// ---
// Gas stove ON
// Gas stove OFF
// Order food online (Dish burnt!)

try-catch-finally flow in every situation

SituationtrycatchfinallyCode after the try statement
No exceptionRuns fullySkippedRunsRuns
Exception matched by a catchRuns until the exceptionRunsRunsRuns
Exception not matchedRuns until the exceptionSkippedRunsSkipped (exception goes to the caller)
return inside tryRuns until returnSkippedRuns before the method returnsSkipped
Exception inside catchRuns until the exceptionRuns until its own exceptionRunsSkipped (new exception goes to the caller)
System.exit(0) inside tryStopsSkippedDoes NOT runSkipped

throw: raising an exception yourself

  • throw creates a problem signal on purpose when your own rule is broken: throw new IllegalArgumentException("message");.
  • You throw an object, so you always write new. Statements after throw in the same block never run.
  • Throwing a checked exception requires the method to catch it or declare it with throws.
  • Real life: a football referee shows a red card. The game stops at that moment and the player must leave.
public class VoterRegistration {
    static void register(String name, int age) {
        if (age < 18) {
            throw new IllegalArgumentException(name + " is " + age + ": must be 18 or older to vote");
        }
        System.out.println(name + " registered as a voter");
    }

    public static void main(String[] args) {
        try {
            register("Asha", 22);
            register("Ravi", 15);    // throws
            register("Kiran", 30);   // skipped
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
// Output:
// Asha registered as a voter
// Rejected: Ravi is 15: must be 18 or older to vote

throws: declaring exceptions a method may pass on

  • throws goes in the method signature and tells callers: this method may pass these checked exceptions to you.
  • The caller must then catch them or declare them again. Unchecked exceptions do not need throws.
  • A method can declare several: void load() throws IOException, SQLException.
  • Real life: a medicine box warning, "may cause drowsiness". The medicine does not handle it; it warns you to plan for it.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReportReader {
    // warns callers: "I may throw IOException"
    static int firstChar(String fileName) throws IOException {
        try (FileReader reader = new FileReader(fileName)) { // closes automatically
            return reader.read();
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(firstChar("report.txt"));
        } catch (FileNotFoundException e) {        // child first
            System.out.println("Report missing: " + e.getMessage());
        } catch (IOException e) {                  // parent after
            System.out.println("Could not read report: " + e.getMessage());
        }
    }
}

Differences between throw and throws

Pointthrowthrows
PurposeActually throws one exception objectDeclares exceptions a method may pass to its caller
PositionInside a method or blockIn the method signature, after the parameters
Followed byAn object: throw new X("msg")Class names: throws IOException, SQLException
How manyOne at a timeMany, separated by commas
Used forSignalling that a rule was brokenPassing checked exceptions up the call stack
Real lifeReferee shows a red cardWarning label on a medicine box
Examplethrow new ArithmeticException("zero");void read() throws IOException

Custom (user-defined) exceptions

  • Create your own exception when built-in names do not describe your business rule: InsufficientBalanceException, InvalidMarksException.
  • Extend Exception for a checked exception (caller must handle it) or RuntimeException for an unchecked one.
  • End the name with Exception. Provide a constructor that takes a message (and optionally a cause), and add fields for extra details.
  • Real life: at an ATM, "insufficient balance" is a normal, expected situation that the customer can fix, so it fits a checked custom exception.
class InsufficientBalanceException extends Exception {     // checked
    private final double shortBy;

    InsufficientBalanceException(String message, double shortBy) {
        super(message);
        this.shortBy = shortBy;
    }

    double getShortBy() {
        return shortBy;
    }
}

class BankAccount {
    private double balance;

    BankAccount(double balance) {
        this.balance = balance;
    }

    void withdraw(double amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException("Insufficient balance", amount - balance);
        }
        balance -= amount;
        System.out.println("Withdrawn Rs." + amount + ", balance Rs." + balance);
    }
}

public class AtmDemo {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount(5000);
        try {
            acc.withdraw(2000);
            acc.withdraw(4000);
        } catch (InsufficientBalanceException e) {
            System.out.println(e.getMessage() + ": short by Rs." + e.getShortBy());
        }
    }
}
// Output:
// Withdrawn Rs.2000.0, balance Rs.3000.0
// Insufficient balance: short by Rs.1000.0

try-with-resources

  • Declare resources in parentheses after try. Java closes them automatically at the end, even when an exception happens.
  • The resource must implement AutoCloseable (files, streams, scanners, database connections all do).
  • Several resources are closed in reverse order of opening. The resource is closed before the catch block runs.
  • Real life: a teacher switches off the projector at the end of class, whether the lesson finished normally or was interrupted.
class Projector implements AutoCloseable {
    private final String room;

    Projector(String room) {
        this.room = room;
        System.out.println("Projector ON in " + room);
    }

    void show(String slide) {
        if (slide.isEmpty()) {
            throw new IllegalArgumentException("Empty slide");
        }
        System.out.println("Showing: " + slide);
    }

    @Override
    public void close() {
        System.out.println("Projector OFF in " + room);   // runs automatically
    }
}

public class ClassroomDemo {
    public static void main(String[] args) {
        try (Projector p = new Projector("Lab 1")) {
            p.show("Exceptions in Java");
            p.show("");                                  // throws
        } catch (IllegalArgumentException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
// Output:
// Projector ON in Lab 1
// Showing: Exceptions in Java
// Projector OFF in Lab 1      (closed BEFORE the catch block runs)
// Caught: Empty slide

Useful methods of Throwable

MethodReturns or doesExample result or use
getMessage()The detail message/ by zero
toString()Class name plus messagejava.lang.ArithmeticException: / by zero
printStackTrace()Prints type, message, and call stack to System.errQuick debugging
getCause()The original exception that was wrappedException chaining
getStackTrace()Array of StackTraceElementCustom logging
getSuppressed()Exceptions suppressed during try-with-resourcesSeeing close() failures
addSuppressed(t)Attaches another exceptionCustom resource handling
initCause(t)Sets the cause after creationOlder exceptions without a cause constructor

Differences between final, finally, and finalize

Pointfinalfinallyfinalize()
What it isKeyword (modifier)Block in exception handlingMethod of Object
Used withVariables, methods, classestry / catchObjects before garbage collection
PurposeConstant value, no overriding, no extendingCleanup code that always runsCleanup before GC (unreliable)
StatusCurrentCurrentDeprecated since Java 9, marked for removal
Examplefinal int MAX = 10;finally { System.out.println("done"); }protected void finalize()
Modern alternativeNot neededtry-with-resources for resourcestry-with-resources or java.lang.ref.Cleaner
L2

Advanced — Exception Handling

Exception propagation through the call stack

  • If a method does not catch an exception, it moves up to the caller, then to its caller, until someone catches it or the thread dies.
  • Unchecked exceptions propagate automatically. Checked exceptions must be declared with throws at each level they pass through.
  • Real life: a customer complaint goes from the counter clerk to the branch manager to head office until someone resolves it.
public class Propagation {
    static void level3() {
        System.out.println("level3 start");
        int zero = 0;
        int x = 10 / zero;                    // exception created here
        System.out.println("level3 end " + x); // skipped
    }

    static void level2() {
        level3();                             // not caught here: passes up
        System.out.println("level2 end");     // skipped
    }

    static void level1() {
        try {
            level2();
        } catch (ArithmeticException e) {     // caught two levels up
            System.out.println("Caught in level1: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        level1();
        System.out.println("main continues");
    }
}
// Output:
// level3 start
// Caught in level1: / by zero
// main continues

Exception chaining: wrap and keep the cause

  • Convert a low-level exception into a meaningful domain exception, but pass the original as the cause.
  • The stack trace then shows both, with "Caused by:" lines, so the real reason is never lost.
class OrderFailedException extends Exception {
    OrderFailedException(String message, Throwable cause) {
        super(message, cause);
    }
}

public class ChainingDemo {
    static int parseQuantity(String text) throws OrderFailedException {
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            throw new OrderFailedException("Invalid quantity in order", e); // wrap and keep cause
        }
    }

    public static void main(String[] args) {
        try {
            parseQuantity("ten");
        } catch (OrderFailedException e) {
            System.out.println(e.getMessage());           // Invalid quantity in order
            System.out.println("Cause: " + e.getCause());  // java.lang.NumberFormatException: For input string: "ten"
        }
    }
}

Suppressed exceptions in try-with-resources

  • If the try body throws and then close() also throws, the body exception is the primary one.
  • The close() exception is not lost: it is attached as a suppressed exception, available through getSuppressed().
class Resource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        throw new Exception("close failed");
    }
}

public class SuppressedDemo {
    public static void main(String[] args) {
        try (Resource r = new Resource()) {
            throw new IllegalStateException("work failed");
        } catch (Exception e) {
            System.out.println("Primary: " + e.getMessage());          // work failed
            for (Throwable s : e.getSuppressed()) {
                System.out.println("Suppressed: " + s.getMessage());   // close failed
            }
        }
    }
}

finally pitfalls

  • A return in finally replaces the value returned by try and silently swallows any exception. Never return from finally.
  • When try returns a primitive, the value is saved before finally runs, so changing the variable in finally does not change the result.
public class FinallyPitfall {
    @SuppressWarnings("finally")
    static int getValue() {
        try {
            return 1;
        } finally {
            return 2;        // overrides the try return (and would hide exceptions)
        }
    }

    static int counter() {
        int x = 10;
        try {
            return x;        // value 10 is saved now
        } finally {
            x = 99;          // does not change the saved return value
        }
    }

    public static void main(String[] args) {
        System.out.println(getValue()); // 2
        System.out.println(counter());  // 10
    }
}

Exception rules for method overriding

  • An overriding method must not throw new or broader checked exceptions than the parent method.
  • It may throw fewer, narrower (subclass), or no checked exceptions, and any unchecked exceptions.
  • Reason: code that calls the parent type only prepared for the parent checked exceptions.
Parent method throwsChild override may throwChild override cannot throw
NothingNothing, or any unchecked exceptionAny checked exception
IOExceptionIOException, FileNotFoundException, nothing, any uncheckedException, or unrelated checked like SQLException
ExceptionException or any subclass, or nothingThrowable
import java.io.FileNotFoundException;
import java.io.IOException;

class Loader {
    void load() throws IOException { }
}

class FileLoader extends Loader {
    @Override
    void load() throws FileNotFoundException { }   // OK: narrower checked exception
}

class MemoryLoader extends Loader {
    @Override
    void load() { }                                // OK: throws nothing
}

// class BadLoader extends Loader {
//     @Override
//     void load() throws Exception { }            // ERROR: overridden method does not throw Exception
// }

public class OverrideRules {
    public static void main(String[] args) throws IOException {
        Loader l = new FileLoader();
        l.load();
        new MemoryLoader().load();
        System.out.println("ok");
    }
}

Preventing NullPointerException and failing fast

  • Prevent unchecked exceptions with checks instead of catching them: test for null, check array length, validate input.
  • Objects.requireNonNull(value, "message") fails immediately with a clear message at the point where bad data enters.
  • Since Java 14, helpful NullPointerException messages name exactly which part of an expression was null.
  • Optional makes "may be missing" explicit in return types.
import java.util.Objects;
import java.util.Optional;

class Address {
    final String city;
    Address(String city) { this.city = city; }
}

class Customer {
    final String name;
    final Address address;

    Customer(String name, Address address) {
        this.name = Objects.requireNonNull(name, "name must not be null"); // fail fast
        this.address = address;                                            // may be null
    }

    Optional<String> city() {
        return Optional.ofNullable(address).map(a -> a.city);
    }
}

public class NullSafety {
    public static void main(String[] args) {
        Customer c = new Customer("Asha", null);
        System.out.println(c.city().orElse("Unknown city"));   // prevent instead of catch

        try {
            new Customer(null, new Address("Hyderabad"));
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());                  // name must not be null
        }
    }
}

Exception handling best practices

DoDo not
Catch the most specific exception you can handleCatch Exception or Throwable everywhere
Use try-with-resources for files, streams, and connectionsClose resources manually and forget one path
Write a helpful message with the bad valueThrow new Exception() with no message
Wrap with a domain exception and pass the causeLose the original exception when rethrowing
Log once, at the boundary that handles itLog and rethrow at every layer
Validate input and prevent unchecked exceptionsUse exceptions for normal control flow
Use checked exceptions for recoverable situationsLeave a catch block empty
Restore the flag after catching InterruptedExceptionSwallow InterruptedException silently
L3

Tricky Interview Points

Q1) What is an exception in Java?

Answer An unwanted event at runtime that disturbs the normal flow. It is an object of a Throwable subclass that holds the problem type, message, and stack trace.

Q2) Give a real-life example of exception handling.

Answer A flat tyre while driving is the exception; using the spare tyre is the handling, so the journey continues. In code, dividing a bill among 0 friends throws ArithmeticException, and a catch block prints a friendly message instead of crashing.

Q3) Explain the exception hierarchy.

Answer Throwable is the root with two children: Error (serious JVM problems) and Exception. Exception subclasses are checked, except RuntimeException and its subclasses, which are unchecked.

Q4) What is the difference between checked and unchecked exceptions?

Answer Checked exceptions are verified by the compiler and must be caught or declared with throws, for example IOException. Unchecked exceptions extend RuntimeException, are not checked by the compiler, and usually indicate programming mistakes, for example NullPointerException.

Q5) What is the difference between an Error and an Exception?

Answer Errors are serious problems like OutOfMemoryError that applications should not try to handle. Exceptions are conditions a program can catch and recover from.

Q6) What happens if an exception is not caught?

Answer It propagates up the call stack. If no method catches it, the default handler prints the stack trace and the thread terminates.

Q7) Can we have try without catch?

Answer Yes, try with finally only, or try-with-resources without catch. A try alone with neither catch nor finally is a compile error.

Q8) In what order should multiple catch blocks be written?

Answer From the most specific to the most general. Putting a parent type before its child causes a compile error because the child catch would be unreachable.

Q9) What is multi-catch?

Answer A Java 7 feature to catch several unrelated exception types in one block using |, for example catch (NumberFormatException | ArithmeticException e). The types cannot be parent and child.

Q10) Does finally always execute?

Answer Almost always: after normal completion, after a caught or uncaught exception, and after return. It does not run if the JVM exits, for example with System.exit() or a crash.

Q11) What happens if finally has a return statement?

Answer It overrides the return value of try or catch and swallows any pending exception. It is legal but considered a bad practice.

Q12) What is the difference between throw and throws?

Answer throw is a statement inside a method that throws one exception object. throws is part of the method signature and declares the checked exceptions the method may pass to its caller.

Q13) How do you create a custom exception?

Answer Extend Exception for a checked exception or RuntimeException for an unchecked one, and provide constructors that call super(message) and optionally super(message, cause).

Q14) What is try-with-resources?

Answer A try statement that declares AutoCloseable resources in parentheses. Java closes them automatically in reverse order, even if an exception occurs.

Q15) What are suppressed exceptions?

Answer When the try body throws and close() also throws in try-with-resources, the close() exception is attached to the primary exception and can be read with getSuppressed().

Q16) What is exception propagation?

Answer The movement of an uncaught exception from the method where it occurred up to its callers until it is caught or reaches the top of the thread.

Q17) What is exception chaining?

Answer Wrapping one exception inside another by passing it as the cause, for example new ServiceException("save failed", e). getCause() returns the original.

Q18) What is the difference between final, finally, and finalize?

Answer final is a modifier for constants, non-overridable methods, and non-extendable classes. finally is a block that runs after try-catch. finalize was an Object method called before garbage collection and is now deprecated.

Q19) Can an overriding method throw a broader checked exception?

Answer No. It can throw the same, narrower, or no checked exceptions. It can always throw unchecked exceptions.

Q20) Can we catch an Error?

Answer Syntactically yes, because Error extends Throwable, but normal application code should not try to recover from errors like OutOfMemoryError.

L4

Simple Programs

Exam marks entry with a custom unchecked exception

class InvalidMarksException extends RuntimeException {
    InvalidMarksException(String message) { super(message); }
}

public class MarksEntry {
    static int validate(String name, String text) {
        int marks;
        try {
            marks = Integer.parseInt(text.trim());
        } catch (NumberFormatException e) {
            throw new InvalidMarksException(name + ": '" + text + "' is not a number");
        }
        if (marks < 0 || marks > 100) {
            throw new InvalidMarksException(name + ": " + marks + " is outside 0-100");
        }
        return marks;
    }

    public static void main(String[] args) {
        String[][] entries = { {"Asha", "87"}, {"Ravi", "105"}, {"Kiran", "ninety"}, {"Meena", " 72 "} };
        int total = 0, valid = 0;
        for (String[] entry : entries) {
            try {
                total += validate(entry[0], entry[1]);
                valid++;
            } catch (InvalidMarksException e) {
                System.out.println("Skipped -> " + e.getMessage());
            }
        }
        System.out.println("Valid entries: " + valid + ", average: " + (total / valid)); // 2, 79
    }
}

Bus seat booking with a checked custom exception

class SeatAlreadyBookedException extends Exception {
    SeatAlreadyBookedException(int seat) {
        super("Seat " + seat + " is already booked");
    }
}

class Bus {
    private final boolean[] booked = new boolean[40];

    void book(int seat) throws SeatAlreadyBookedException {
        if (seat < 1 || seat > booked.length) {
            throw new IllegalArgumentException("Seat " + seat + " does not exist (1-" + booked.length + ")");
        }
        if (booked[seat - 1]) {
            throw new SeatAlreadyBookedException(seat);
        }
        booked[seat - 1] = true;
        System.out.println("Seat " + seat + " booked");
    }
}

public class BusBooking {
    public static void main(String[] args) {
        Bus bus = new Bus();
        int[] requests = { 12, 12, 41, 7 };
        for (int seat : requests) {
            try {
                bus.book(seat);
            } catch (SeatAlreadyBookedException e) {
                System.out.println("Sorry: " + e.getMessage());
            } catch (IllegalArgumentException e) {
                System.out.println("Invalid: " + e.getMessage());
            }
        }
    }
}

Safe calculator

public class SafeCalculator {
    static int calculate(String a, char op, String b) {
        int x = Integer.parseInt(a);
        int y = Integer.parseInt(b);
        return switch (op) {
            case '+' -> x + y;
            case '-' -> x - y;
            case '*' -> x * y;
            case '/' -> x / y;
            default -> throw new UnsupportedOperationException("Unknown operator " + op);
        };
    }

    public static void main(String[] args) {
        String[][] jobs = { {"20", "/", "4"}, {"9", "/", "0"}, {"7", "x", "2"}, {"ten", "+", "1"} };
        for (String[] j : jobs) {
            String expr = String.join(" ", j);
            try {
                System.out.println(expr + " = " + calculate(j[0], j[1].charAt(0), j[2]));
            } catch (ArithmeticException e) {
                System.out.println(expr + " -> cannot divide by zero");
            } catch (NumberFormatException e) {
                System.out.println(expr + " -> numbers only, please");
            } catch (UnsupportedOperationException e) {
                System.out.println(expr + " -> " + e.getMessage());
            }
        }
    }
}

Retry a failing network call

class NetworkException extends Exception {
    NetworkException(String message) { super(message); }
}

public class RetryDemo {
    private static int calls = 0;

    static String fetchPrice() throws NetworkException {
        calls++;
        if (calls < 3) {                          // first two calls fail
            throw new NetworkException("Timeout on attempt " + calls);
        }
        return "Rs.72,450";
    }

    public static void main(String[] args) {
        int maxAttempts = 4;
        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                System.out.println("Gold price: " + fetchPrice());
                break;                             // success: stop retrying
            } catch (NetworkException e) {
                System.out.println(e.getMessage() + ", retrying...");
            } finally {
                System.out.println("Attempt " + attempt + " finished");
            }
        }
    }
}

Read a file safely with try-with-resources

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class ReadMarks {
    public static void main(String[] args) {
        Path file = Path.of("marks.txt");
        try (BufferedReader reader = Files.newBufferedReader(file)) {
            String line;
            int lineNo = 0;
            while ((line = reader.readLine()) != null) {
                lineNo++;
                System.out.println(lineNo + ": " + line);
            }
        } catch (NoSuchFileException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
        }
        System.out.println("Done");
    }
}

Password validator with a custom exception

class WeakPasswordException extends Exception {
    WeakPasswordException(String reason) {
        super("Weak password: " + reason);
    }
}

public class PasswordCheck {
    static void validate(String pwd) throws WeakPasswordException {
        if (pwd.length() < 8) {
            throw new WeakPasswordException("needs at least 8 characters");
        }
        if (pwd.chars().noneMatch(Character::isDigit)) {
            throw new WeakPasswordException("needs a digit");
        }
        if (pwd.chars().noneMatch(Character::isUpperCase)) {
            throw new WeakPasswordException("needs an uppercase letter");
        }
    }

    public static void main(String[] args) {
        String[] attempts = { "java", "javaguru", "javaguru7", "JavaGuru7" };
        for (String p : attempts) {
            try {
                validate(p);
                System.out.println(p + " -> accepted");
            } catch (WeakPasswordException e) {
                System.out.println(p + " -> " + e.getMessage());
            }
        }
    }
}

Predict the output: try, catch, finally order

public class FlowQuiz {
    static void test(int n) {
        try {
            System.out.print("A ");
            if (n == 0) {
                throw new RuntimeException("boom");
            }
            System.out.print("B ");
        } catch (RuntimeException e) {
            System.out.print("C ");
        } finally {
            System.out.print("D ");
        }
        System.out.println("E");
    }

    public static void main(String[] args) {
        test(1); // A B D E
        test(0); // A C D E
    }
}
L5

Problem Solving Tricks

  • Hierarchy in one line: Throwable splits into Error and Exception; Exception minus RuntimeException = checked.
  • Checked = outside world problems (file, network, database). Unchecked = your own bugs (null, index, cast).
  • Write catch blocks from child to parent: FileNotFoundException before IOException before Exception.
  • throw is followed by an object (new); throws is followed by class names.
  • finally runs even after return; only System.exit() or a JVM crash stops it.
  • Prefer try-with-resources over finally for closing anything AutoCloseable.
  • Never leave a catch block empty. At minimum log the message.
  • Always pass the cause when wrapping: new MyException("msg", e).
  • Prevent unchecked exceptions with checks (if (x != null), i < arr.length) instead of catching them.
  • Never return from finally; it hides exceptions and changes results.
L6

Practice Programs List

  1. Write a bill splitter that divides an amount by the number of friends and handles zero friends with ArithmeticException.
  2. Parse ages from a String array and catch NumberFormatException for non-numeric values.
  3. Create an array of 5 seats and catch ArrayIndexOutOfBoundsException when seat 6 is requested.
  4. Write one try with three catch blocks (number format, array index, arithmetic) and a final catch (Exception e).
  5. Rewrite the previous program using multi-catch and compare the code.
  6. Show that finally prints even when you return inside try.
  7. Write register(age) that throws IllegalArgumentException for age below 18.
  8. Propagate an IOException from a helper method to main using throws.
  9. Create a checked InsufficientBalanceException and force the caller of withdraw to handle it.
  10. Create an unchecked InvalidMarksException for marks outside 0 to 100.
  11. Create an AutoCloseable class that prints on open and close, and use two of them in one try-with-resources. Note the close order.
  12. Print the stack trace of an exception thrown three method calls deep, and explain each line.
  13. Wrap a NumberFormatException inside your own exception and print getCause().
  14. Draw the exception hierarchy from memory with at least four checked and four unchecked exceptions.