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.
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).
| Term | Meaning | Real-life comparison |
|---|---|---|
| Exception | A problem the program can catch and recover from | Flat tyre on the way to office |
| Exception handling | Code that responds to the problem | Using the spare tyre |
| Error | A serious JVM or system problem, usually not recoverable | The road is washed away by a flood |
| Stack trace | The list of method calls active when the exception happened | The route map showing where you broke down |
| Unhandled exception | No matching catch, so the thread stops | No 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.
| Exception | Small real-life example | Java code that causes it | Type |
|---|---|---|---|
ArithmeticException | Splitting a Rs.1200 bill among 0 friends | int share = 1200 / friends; with friends = 0 | Unchecked |
NullPointerException | Calling a contact whose phone number is empty | String phone = null; phone.length(); | Unchecked |
ArrayIndexOutOfBoundsException | Asking for seat 51 in a 50-seat bus | int[] seats = new int[50]; seats[50] = 1; | Unchecked |
StringIndexOutOfBoundsException | Reading the 10th letter of the word "Java" | "Java".charAt(10); | Unchecked |
NumberFormatException | Typing "twenty" in an age box that expects digits | Integer.parseInt("twenty"); | Unchecked |
ClassCastException | Treating a dog as if it were a cat | Object o = "hi"; Integer i = (Integer) o; | Unchecked |
IllegalArgumentException | Ordering -3 pizzas | throw new IllegalArgumentException("qty must be at least 1"); | Unchecked |
InputMismatchException | Entering letters when the form asks for a PIN | new Scanner("abc").nextInt(); | Unchecked |
FileNotFoundException | Opening a document that was deleted | new FileReader("missing.txt"); | Checked |
IOException | Internet cut while downloading a file | Reading from a broken network stream | Checked |
SQLException | The bank database server is down | DriverManager.getConnection(url) fails | Checked |
InterruptedException | Someone wakes you up while you are sleeping | Thread.sleep(1000) is interrupted | Checked |
OutOfMemoryError | Pouring 2 litres of water into a 1-litre bottle | Adding objects to a list forever | Error |
StackOverflowError | Two mirrors facing each other: endless reflections | A recursive method with no base case | Error |
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
Throwableis the root of everything that can be thrown or caught. It has two direct children:ErrorandException.Error: serious JVM problems such asOutOfMemoryErrorandStackOverflowError. Do not catch them in normal code.Exception: problems a program may want to handle. Its subclasses (exceptRuntimeException) are checked exceptions.RuntimeExceptionand 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)catchesIOExceptionandNullPointerException.
| Class | Direct parent | Type | Thrown when |
|---|---|---|---|
Throwable | Object | Root | Superclass of every exception and error |
Error | Throwable | Error | Serious JVM or system problem |
OutOfMemoryError | VirtualMachineError | Error | The heap is full |
StackOverflowError | VirtualMachineError | Error | Recursion goes too deep |
Exception | Throwable | Checked | Conditions a program may want to catch |
IOException | Exception | Checked | Input or output fails |
FileNotFoundException | IOException | Checked | A file cannot be opened |
SQLException | Exception | Checked | Database access fails |
ClassNotFoundException | ReflectiveOperationException | Checked | A class cannot be found by name at runtime |
InterruptedException | Exception | Checked | A sleeping or waiting thread is interrupted |
RuntimeException | Exception | Unchecked | Parent of programming-error exceptions |
ArithmeticException | RuntimeException | Unchecked | Integer division by zero |
NullPointerException | RuntimeException | Unchecked | Using a null reference |
ArrayIndexOutOfBoundsException | IndexOutOfBoundsException | Unchecked | Invalid array index |
NumberFormatException | IllegalArgumentException | Unchecked | Text is not a valid number |
ClassCastException | RuntimeException | Unchecked | Invalid 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.
- Error:
OutOfMemoryError,StackOverflowError— do not catch in normal code. - Checked:
IOException,SQLException,InterruptedException— compiler forces catch orthrows. - 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
| Point | Checked exception | Unchecked exception | Error |
|---|---|---|---|
| Superclass | Exception (but not RuntimeException) | RuntimeException | Error |
| Checked by the compiler? | Yes: must catch or declare with throws | No | No |
| When it happens | At runtime, but the compiler forces you to plan for it | At runtime | At runtime |
| Usual cause | Things outside the program: files, network, database | Programming mistakes: null, bad index, bad cast | JVM or system failure |
| Recoverable? | Usually: retry, ask for another file | Fix the code | Usually not |
| Examples | IOException, SQLException, InterruptedException | NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException | OutOfMemoryError, StackOverflowError |
| Real life | The train may be late, so plan a backup | Forgetting your ticket: your own mistake | An earthquake: nothing you can do |
| Should you catch it? | Yes, or declare it | Prevent with checks; catch at boundaries | No |
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 matchingcatchblock and skips the rest oftry. - The catch parameter (
e) is the exception object. Usee.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
finallyruns whether the try block succeeds, an exception is caught, or an exception escapes. It even runs afterreturn.- 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
| Situation | try | catch | finally | Code after the try statement |
|---|---|---|---|---|
| No exception | Runs fully | Skipped | Runs | Runs |
| Exception matched by a catch | Runs until the exception | Runs | Runs | Runs |
| Exception not matched | Runs until the exception | Skipped | Runs | Skipped (exception goes to the caller) |
return inside try | Runs until return | Skipped | Runs before the method returns | Skipped |
| Exception inside catch | Runs until the exception | Runs until its own exception | Runs | Skipped (new exception goes to the caller) |
System.exit(0) inside try | Stops | Skipped | Does NOT run | Skipped |
throw: raising an exception yourself
throwcreates 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 afterthrowin 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
throwsgoes 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
| Point | throw | throws |
|---|---|---|
| Purpose | Actually throws one exception object | Declares exceptions a method may pass to its caller |
| Position | Inside a method or block | In the method signature, after the parameters |
| Followed by | An object: throw new X("msg") | Class names: throws IOException, SQLException |
| How many | One at a time | Many, separated by commas |
| Used for | Signalling that a rule was broken | Passing checked exceptions up the call stack |
| Real life | Referee shows a red card | Warning label on a medicine box |
| Example | throw 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
Exceptionfor a checked exception (caller must handle it) orRuntimeExceptionfor 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
| Method | Returns or does | Example result or use |
|---|---|---|
getMessage() | The detail message | / by zero |
toString() | Class name plus message | java.lang.ArithmeticException: / by zero |
printStackTrace() | Prints type, message, and call stack to System.err | Quick debugging |
getCause() | The original exception that was wrapped | Exception chaining |
getStackTrace() | Array of StackTraceElement | Custom logging |
getSuppressed() | Exceptions suppressed during try-with-resources | Seeing close() failures |
addSuppressed(t) | Attaches another exception | Custom resource handling |
initCause(t) | Sets the cause after creation | Older exceptions without a cause constructor |
Differences between final, finally, and finalize
| Point | final | finally | finalize() |
|---|---|---|---|
| What it is | Keyword (modifier) | Block in exception handling | Method of Object |
| Used with | Variables, methods, classes | try / catch | Objects before garbage collection |
| Purpose | Constant value, no overriding, no extending | Cleanup code that always runs | Cleanup before GC (unreliable) |
| Status | Current | Current | Deprecated since Java 9, marked for removal |
| Example | final int MAX = 10; | finally { System.out.println("done"); } | protected void finalize() |
| Modern alternative | Not needed | try-with-resources for resources | try-with-resources or java.lang.ref.Cleaner |
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
throwsat 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 throughgetSuppressed().
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
returninfinallyreplaces the value returned bytryand silently swallows any exception. Never return from finally. - When
tryreturns a primitive, the value is saved beforefinallyruns, 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 throws | Child override may throw | Child override cannot throw |
|---|---|---|
| Nothing | Nothing, or any unchecked exception | Any checked exception |
IOException | IOException, FileNotFoundException, nothing, any unchecked | Exception, or unrelated checked like SQLException |
Exception | Exception or any subclass, or nothing | Throwable |
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.
Optionalmakes "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
| Do | Do not |
|---|---|
| Catch the most specific exception you can handle | Catch Exception or Throwable everywhere |
| Use try-with-resources for files, streams, and connections | Close resources manually and forget one path |
| Write a helpful message with the bad value | Throw new Exception() with no message |
| Wrap with a domain exception and pass the cause | Lose the original exception when rethrowing |
| Log once, at the boundary that handles it | Log and rethrow at every layer |
| Validate input and prevent unchecked exceptions | Use exceptions for normal control flow |
| Use checked exceptions for recoverable situations | Leave a catch block empty |
Restore the flag after catching InterruptedException | Swallow InterruptedException silently |
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.
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
}
} 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:
FileNotFoundExceptionbeforeIOExceptionbeforeException. - 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.
Practice Programs List
- Write a bill splitter that divides an amount by the number of friends and handles zero friends with
ArithmeticException. - Parse ages from a String array and catch
NumberFormatExceptionfor non-numeric values. - Create an array of 5 seats and catch
ArrayIndexOutOfBoundsExceptionwhen seat 6 is requested. - Write one try with three catch blocks (number format, array index, arithmetic) and a final
catch (Exception e). - Rewrite the previous program using multi-catch and compare the code.
- Show that
finallyprints even when youreturninsidetry. - Write
register(age)that throwsIllegalArgumentExceptionfor age below 18. - Propagate an
IOExceptionfrom a helper method tomainusingthrows. - Create a checked
InsufficientBalanceExceptionand force the caller ofwithdrawto handle it. - Create an unchecked
InvalidMarksExceptionfor marks outside 0 to 100. - Create an
AutoCloseableclass that prints on open and close, and use two of them in one try-with-resources. Note the close order. - Print the stack trace of an exception thrown three method calls deep, and explain each line.
- Wrap a
NumberFormatExceptioninside your own exception and printgetCause(). - Draw the exception hierarchy from memory with at least four checked and four unchecked exceptions.