You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Errors happen — files are missing, networks time out, users provide invalid input. Java's exception handling mechanism gives you a structured way to detect, respond to, and recover from errors. This lesson also covers reading and writing files.
Throwable
├── Error (serious — don't catch: OutOfMemoryError, StackOverflowError)
└── Exception
├── IOException (checked)
├── SQLException (checked)
├── FileNotFoundException (checked)
└── RuntimeException (unchecked)
├── NullPointerException
├── ArrayIndexOutOfBoundsException
├── IllegalArgumentException
├── ArithmeticException
└── ClassCastException
| Type | Checked | Unchecked (Runtime) |
|---|---|---|
| Must handle? | Yes — compiler enforces try/catch or throws | No — compiler does not enforce |
| Caused by | External factors (I/O, network, database) | Programming errors (null access, bad cast) |
| Extends | Exception (but not RuntimeException) | RuntimeException |
| Examples | IOException, SQLException | NullPointerException, ArithmeticException |
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This always executes");
}
try {
// risky code
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected error: " + e.getMessage());
}
try {
// risky code
} catch (IOException | SQLException e) {
System.out.println("Error: " + e.getMessage());
}
public static int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
For checked exceptions, declare them in the method signature:
public static String readFile(String path) throws IOException {
return Files.readString(Path.of(path));
}
public class InsufficientFundsException extends Exception {
private final double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds: " + amount);
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
// Usage:
if (amount > balance) {
throw new InsufficientFundsException(amount);
}
Resources that implement AutoCloseable are automatically closed:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.