Exception Handling Basics in Java
π The Story of the Safety Net
Imagine youβre a circus performer walking on a tightrope. Whatβs below you? A safety net! If you slip and fall, the net catches you. You donβt crash to the ground.
Exception Handling in Java is exactly like that safety net.
When your program runs, sometimes things go wrong. A file might be missing. A number might be divided by zero. A network connection might fail. Without a safety net, your program crashes. With exception handling, your program recovers gracefully.
π Exception Fundamentals
What is an Exception?
An exception is an unexpected problem that happens while your program runs.
Think of it like this:
- Youβre making a sandwich (your program is running)
- You reach for bread, but the jar is empty! (an exception occurs)
- Without handling: You panic and give up (program crashes)
- With handling: You calmly go buy more bread (program recovers)
Real Examples of Exceptions
| What You Try | What Goes Wrong | Exception Type |
|---|---|---|
| Open a file | File doesnβt exist | FileNotFoundException |
| Divide 10 by 0 | Math error | ArithmeticException |
| Access array[10] | Array has only 5 items | ArrayIndexOutOfBoundsException |
| Convert βhelloβ to number | Not a number | NumberFormatException |
Errors vs Exceptions
Problems in Java
β
βββ Errors (serious, can't fix)
β βββ Computer ran out of memory
β
βββ Exceptions (can handle!)
βββ Checked (must handle)
βββ Unchecked (optional)
Errors = House on fire. Call firefighters. Exceptions = Spilled milk. Clean it up yourself.
π― The try-catch Block
Your First Safety Net
The try-catch block is your primary tool. It says:
- try = βAttempt this risky codeβ
- catch = βIf something goes wrong, do this insteadβ
Simple Example
try {
int result = 10 / 0; // Risky!
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Oops! Can't divide by zero!");
}
What happens:
- Java tries to divide 10 by 0
- Thatβs impossible! Exception occurs!
- Java catches the problem
- Instead of crashing, it prints our friendly message
Real-World Analogy
try {
Walk across the room blindfolded
} catch (BumpIntoChairException e) {
Say "Found a chair!" and walk around it
}
Catching Multiple Exceptions
Sometimes different things can go wrong. Catch them separately!
try {
int[] numbers = {1, 2, 3};
int x = numbers[10]; // Problem 1?
int y = 10 / 0; // Problem 2?
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array too small!");
} catch (ArithmeticException e) {
System.out.println("Math error!");
}
The Exception Object
When you catch an exception, you get information about what went wrong:
catch (Exception e) {
e.getMessage(); // Short description
e.printStackTrace(); // Full error details
}
π The finally Block
The βAlways Do Thisβ Section
Sometimes you need to do something no matter what happens. Enter finally.
Analogy: When you borrow a library book:
- try = Read the book
- catch = Handle if pages are torn
- finally = ALWAYS return the book!
Example
try {
// Open a file
// Read from file
} catch (Exception e) {
System.out.println("Error reading file!");
} finally {
// Close the file - ALWAYS happens!
System.out.println("Cleaning up...");
}
When Does finally Run?
| Scenario | Does finally run? |
|---|---|
| try succeeds | β YES |
| catch handles error | β YES |
| Exception not caught | β YES |
| Return in try | β YES |
| System.exit() called | β NO |
finally is unstoppable! (almost)
The Complete Pattern
try {
// 1. Risky code here
} catch (SpecificException e) {
// 2. Handle specific problem
} catch (Exception e) {
// 3. Handle any other problem
} finally {
// 4. Always clean up
}
πͺ The throw Keyword
Creating Your Own Exceptions
Sometimes YOU want to signal a problem. Use throw!
Analogy: Youβre a referee. When a player breaks a rule, you blow your whistle and throw a flag!
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException(
"Age cannot be negative!"
);
}
this.age = age;
}
How throw Works
Your Code Java Runtime
β β
β throw Exception β
β βββββββββββββββΊ β
β β Stops normal flow
β β Looks for catch
β βββββββββββββ β
β (caught or crash) β
Common Throw Patterns
Validation:
if (name == null) {
throw new NullPointerException(
"Name cannot be null"
);
}
Business Rules:
if (balance < amount) {
throw new InsufficientFundsException(
"Not enough money!"
);
}
π The throws Keyword
Passing the Problem Up
Sometimes you donβt want to handle an exception yourself. You want to warn others: βHey, this method might cause problems!β
Analogy:
throw= Actually throwing a ballthrows= Putting up a sign: βWarning: Balls may fly here!β
Syntax
public void readFile(String path)
throws FileNotFoundException {
// Code that might fail
FileReader file = new FileReader(path);
}
throw vs throws
| Feature | throw | throws |
|---|---|---|
| What it does | Creates exception | Declares warning |
| Where used | Inside method | In method signature |
| Number | One at a time | Can list multiple |
Multiple throws
public void riskyMethod()
throws IOException,
SQLException,
ParseException {
// Multiple things could go wrong
}
Who Must Handle It?
When you use throws, the caller must either:
- Catch the exception, OR
- Declare
throwsthemselves
// Option 1: Catch it
public void caller() {
try {
riskyMethod();
} catch (IOException e) {
// Handle it
}
}
// Option 2: Pass it up
public void caller() throws IOException {
riskyMethod();
}
π³ Exception Hierarchy
The Family Tree
All exceptions in Java belong to a family tree:
graph TD A["Throwable"] --> B["Error"] A --> C["Exception"] B --> D["OutOfMemoryError"] B --> E["StackOverflowError"] C --> F["RuntimeException"] C --> G["IOException"] C --> H["SQLException"] F --> I["NullPointerException"] F --> J["ArithmeticException"] F --> K["ArrayIndexOutOfBoundsException"]
Understanding the Levels
Level 1: Throwable
- The grandparent of all problems
- Everything extends this
Level 2: Error vs Exception
- Error = Serious. System-level. Donβt catch.
- Exception = Your problems. You CAN handle.
Level 3: Checked vs Unchecked
| Type | Must Handle? | Examples |
|---|---|---|
| Checked | β Yes, always | IOException, SQLException |
| Unchecked | β Optional | NullPointerException |
Why Does This Matter?
Catch order matters! Catch specific exceptions first:
// β
CORRECT - Specific first
catch (FileNotFoundException e) { }
catch (IOException e) { }
// β WRONG - General catches everything
catch (IOException e) { }
catch (FileNotFoundException e) { } // Never reached!
Quick Reference
Unchecked (RuntimeException)
βββ NullPointerException
βββ ArithmeticException
βββ IllegalArgumentException
βββ ArrayIndexOutOfBoundsException
Checked (must handle or declare)
βββ IOException
βββ FileNotFoundException
βββ SQLException
βββ ParseException
π― Putting It All Together
The Complete Picture
public class SafeCalculator {
public double divide(int a, int b)
throws IllegalArgumentException {
// THROW: Create exception if invalid
if (b == 0) {
throw new IllegalArgumentException(
"Cannot divide by zero!"
);
}
return (double) a / b;
}
public void calculate() {
// TRY: Attempt risky operation
try {
double result = divide(10, 0);
System.out.println("Result: " + result);
// CATCH: Handle the problem
} catch (IllegalArgumentException e) {
System.out.println("Error: " +
e.getMessage());
// FINALLY: Always clean up
} finally {
System.out.println("Calculation done!");
}
}
}
π‘ Remember This!
- try-catch = Your safety net for risky code
- finally = βAlways do thisβ (cleanup crew)
- throw = Create and throw an exception
- throws = Warning label on methods
- Hierarchy = Catch specific before general
Youβre now ready to write code that handles problems gracefully instead of crashing! π
