Java — Exceptions
Basic try-catch
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Multiple catch blocks
try {
String s = null;
s.length();
} catch (NullPointerException e) {
System.out.println("Null pointer");
} catch (Exception e) {
System.out.println("General error");
} finally {
System.out.println("Always runs");
}
Custom exceptions
class InsufficientFundsException extends Exception {
private double amount;
InsufficientFundsException(double amount) {
super("Insufficient funds: need " + amount);
this.amount = amount;
}
double getAmount() { return amount; }
}
class BankAccount {
private double balance;
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
}
Try-with-resources
import java.io.*;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} // Auto-closed
Common exceptions
| Exception | When |
|---|---|
NullPointerException | Null reference |
ArrayIndexOutOfBoundsException | Invalid array index |
ClassNotFoundException | Class not found |
IOException | I/O error |
NumberFormatException | Invalid number format |
IllegalArgumentException | Invalid argument |
IllegalStateException | Invalid state |
Mini Practice
Write Java code that:
- Creates a custom exception
- Uses try-with-resources for file operations
- Demonstrates multi-catch with
|
Up Next
In the next lesson, you'll learn about Collections — Lists, Sets, and Maps.
Related Topics
Frequently Asked Questions about Exceptions
What is Exceptions in Java?
Exceptions is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Exceptions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Exceptions.
Why is Exceptions important in Java?
Exceptions is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.