Chapter 16: Exception Handling

In real-world applications (especially in Mumbai’s fast-paced tech world ☕), things go wrong all the time: user enters wrong input, file not found, database down, network timeout… If you don’t handle these exceptions, your program will crash and show ugly stack traces to the user.

Exception handling lets you:

  • Catch errors gracefully
  • Recover or inform the user
  • Clean up resources properly
  • Log issues for debugging

We’ll go super slowly, with lots of real-life analogies, complete runnable programs, step-by-step breakdowns, tables, common mistakes with fixes, and tons of examples you can copy-paste and run right now.

Let’s dive in!

1. What is an Exception? (The Big Idea)

An exception is an event that disrupts the normal flow of a program. Java provides a hierarchy of Exception classes (all inherit from Throwable):

text

Real-life analogy: You’re riding a bike in Mumbai traffic.

  • A pothole (unexpected event) → you fall (exception)
  • If you wear helmet & knee pads (try-catch) → you get hurt less
  • If you ignore it → crash badly!

2. try-catch-finally (The Core Structure)

Syntax:

Java

Example 1: Basic try-catch

Java

Output:

text

Example 2: Multiple catch blocks + finally

Java

Test cases:

  • Enter 0 → “Cannot divide by zero!” + finally
  • Enter abc → “Please enter a valid number!” + finally
  • Enter 5 → “Result: 20” + finally

3. throw and throws (Manually Throwing & Declaring)

throw → manually throw an exception throws → declare that a method might throw checked exceptions

Example 3: throw + throws

Java

Output:

text

throws is mandatory for checked exceptions (e.g., IOException, SQLException). For unchecked (RuntimeException & subclasses) → optional.

4. Custom Exceptions (Your Own Exception Classes)

You can create your own exceptions by extending Exception (checked) or RuntimeException (unchecked).

Example 4: Custom Exception – InvalidBalanceException

Java

Using them:

Java

Test:

Java

5. try-with-resources (Java 7+) – Automatic Resource Management

Very useful for files, database connections, sockets — resources that need to be closed properly.

Syntax:

Java

Example 5: Reading a file safely

Java

Benefit: No need to write finally { if (br != null) br.close(); }

Quick Recap Table (Your Cheat Sheet)

Concept Key Points / Best Practice Example
try-catch Catch specific exceptions first, general last catch (ArithmeticException e)
finally Always runs — cleanup (close files, connections) Close Scanner, FileReader
throw Manually throw exception throw new IllegalArgumentException(“…”)
throws Declare checked exceptions in method signature throws IOException
Custom Exception Extend Exception (checked) or RuntimeException InsufficientFundsException
try-with-resources Auto-close resources (Java 7+) try (BufferedReader br = …)

Common Mistakes & Fixes

Mistake Problem Fix
Catching Exception first Specific catches never reached Catch specific → general (Exception) last
Not closing resources Resource leak (file handles, connections) Use try-with-resources or finally
Throwing checked exception without throws Compile error Add throws or handle with try-catch
Empty catch block Silent failure — bugs hidden At least log: e.printStackTrace()
Catching Error Usually don’t — serious JVM issues Only catch Exception & subclasses

Homework for You (Practice to Master!)

  1. Basic: Write a method that divides two numbers — handle ArithmeticException and InputMismatchException.
  2. Medium: Create custom exception NegativeNumberException. Throw it if user enters negative age.
  3. Advanced: Write a program that reads numbers from a file using try-with-resources. Handle FileNotFoundException and IOException.
  4. Fun: Create a method withdrawMoney(double amount) that throws InsufficientFundsException if balance is low.
  5. Challenge: Fix this buggy code:
    Java

You’re doing fantastic! Exception handling is what separates toy programs from production-ready, enterprise-grade code — now your programs can survive real-world chaos!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *