Exception Handling
Exception handling makes programs more robust. This lesson covers Java's exception handling mechanism.
What is an Exception
An exception is an error that occurs during program execution.
Exception Classification
TEXT
Throwable
├── Error (serious errors, program cannot handle)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception (exceptions, program can handle)
├── Checked exceptions (must handle)
│ ├── IOException
│ └── SQLException
└── Unchecked exceptions (RuntimeException)
├── NullPointerException
├── ArrayIndexOutOfBoundsException
└── NumberFormatException
try-catch
Syntax
JAVA
try {
// Code that may throw an exception
} catch (ExceptionType variableName) {
// Handle the exception
}
Example: Basic Exception Handling
JAVA
public class TryCatchDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
System.out.println("Program continues");
}
}
Output:
TEXT
Arithmetic error: / by zero
Program continues
Multiple catch Blocks
JAVA
try {
// Code that may throw multiple exceptions
} catch (ExceptionType1 e1) {
// Handle exception 1
} catch (ExceptionType2 e2) {
// Handle exception 2
} catch (Exception e) {
// Handle other exceptions
}
Example: Multiple catch
JAVA
public class MultiCatch {
public static void main(String[] args) {
try {
String s = "abc";
int num = Integer.parseInt(s);
int result = 10 / num;
} catch (NumberFormatException e) {
System.out.println("Number format error: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Other error: " + e.getMessage());
}
}
}
try-catch-finally
The finally block always executes, whether an exception occurs or not.
Syntax
JAVA
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Always executes
}
Example: finally
JAVA
public class FinallyDemo {
public static void main(String[] args) {
try {
System.out.println("try block");
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("catch block");
} finally {
System.out.println("finally block");
}
}
}
Output:
TEXT
try block
catch block
finally block
Example: Resource Release
JAVA
import java.io.*;
public class ResourceDemo {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("test.txt");
// Read file
} catch (FileNotFoundException e) {
System.out.println("File not found");
} finally {
// Release resource
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
try-with-resources
Introduced in Java 7, automatically closes resources.
Syntax
JAVA
try (ResourceType variable = new Resource()) {
// Use resource
} catch (ExceptionType e) {
// Handle exception
}
Example: try-with-resources
JAVA
import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
// Automatically closes resource
try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
// reader automatically closed, no finally needed
}
}
throw and throws
throw: Throw an Exception
JAVA
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
throws: Declare an Exception
JAVA
public static void readFile(String path) throws FileNotFoundException {
FileReader reader = new FileReader(path);
}
Example: throw and throws
JAVA
public class ThrowDemo {
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
public static void validateAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Invalid age: " + age);
}
}
public static void main(String[] args) {
try {
System.out.println(divide(10, 0));
} catch (ArithmeticException e) {
System.out.println(e.getMessage()); // Cannot divide by zero
}
try {
validateAge(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // Invalid age: -5
}
}
}
Custom Exceptions
Steps
- Extend Exception or RuntimeException
- Provide constructors
Example: Custom Exception
JAVA
// Custom exception class
public class InsufficientBalanceException extends Exception {
private double balance;
private double amount;
public InsufficientBalanceException(double balance, double amount) {
super("Insufficient balance: " + balance + ", withdrawal: " + amount);
this.balance = balance;
this.amount = amount;
}
public double getBalance() {
return balance;
}
public double getAmount() {
return amount;
}
}
// Using custom exception
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException(balance, amount);
}
balance -= amount;
System.out.println("Withdrawal successful, balance: " + balance);
}
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
try {
account.withdraw(500); // Withdrawal successful, balance: 500.0
account.withdraw(800); // Throws exception
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
System.out.println("Balance: " + e.getBalance());
System.out.println("Withdrawal: " + e.getAmount());
}
}
}
Common Exceptions
| Exception | Description | Cause |
|---|---|---|
NullPointerException |
Null pointer | Calling method on null object |
ArrayIndexOutOfBoundsException |
Array index out of bounds | Accessing non-existent index |
NumberFormatException |
Number format error | String to number conversion failed |
ClassCastException |
Class cast error | Downcast type mismatch |
ArithmeticException |
Arithmetic error | Dividing by zero |
FileNotFoundException |
File not found | Wrong file path |
IOException |
IO error | File read/write failed |
Exception Handling Principles
| Principle | Description |
|---|---|
| Specific exceptions first | Catch specific exceptions before general ones |
| Don't ignore exceptions | At least log them |
| Use finally for resources | Or use try-with-resources |
| Don't use exceptions for flow control | Exceptions are for errors, not control flow |
❓ Frequently Asked Questions
Q What's the difference between Error and Exception?
A Error is a serious problem that the program cannot handle. Exception is a problem that the program can catch and handle.
Q What's the difference between checked and unchecked exceptions?
A Checked exceptions must be handled (try-catch or throws). Unchecked exceptions don't need to be handled.
Q When should I create custom exceptions?
A When you need to distinguish business exception types, like insufficient balance or user not found.
📖 Summary
- Exceptions are errors that occur during program execution
- try-catch catches exceptions, finally releases resources
- throw throws exceptions, throws declares exceptions
- try-with-resources automatically closes resources
- Custom exceptions extend Exception or RuntimeException
📝 Exercises
- Exception handling: Write a method to read a file, handling file not found and read errors
- Custom exception: Define an AgeOutOfBoundsException for age validation
- Resource management: Use try-with-resources to implement file copying
Next Lesson
In the next lesson, we'll learn about Practice: OOP — applying object-oriented knowledge.



