Exception Handling
Exception Handling
Introduction
In this lesson, you'll learn about exception handling in Java. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with exception handling.
Java has its own approach to exception handling, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
// try / catch / finally (no else block)
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (IllegalArgumentException | NullPointerException e) {
System.out.println("Combined catch: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
// Throw
static void validate(int age) throws IllegalArgumentException {
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
}
// Custom exception (checked)
class AppError extends Exception {
int code;
public AppError(int code, String msg) {
super(msg);
this.code = code;
}
}
// try-with-resources (auto-close)
try (var reader = new BufferedReader(new FileReader("f.txt"))) {
String line = reader.readLine();
}Comparing to Python
Here's how you might have written similar code in Python:
# try / except / else / finally
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type/Value error: {e}")
else:
print("No error!")
finally:
print("Always runs")
# Raise
def validate(age):
if age < 0:
raise ValueError("Age cannot be negative")
# Custom exception
class AppError(Exception):
def __init__(self, code, msg):
super().__init__(msg)
self.code = codeYou may be used to different syntax or behavior.
Python except → Java catch; Python allows multiple except, Java allows multiple catch
You may be used to different syntax or behavior.
Python has an else block (no exception); Java does not
You may be used to different syntax or behavior.
Java has checked exceptions that must be declared with throws in the method signature
You may be used to different syntax or behavior.
Multi-catch in Java uses | to combine exception types
You may be used to different syntax or behavior.
Java try-with-resources automatically closes AutoCloseable objects
Step-by-Step Breakdown
1. try/catch vs try/except
The structure is nearly identical. except becomes catch, and the exception variable uses parentheses.
try:
x = 1 / 0
except ZeroDivisionError as e:
print(e)try {
int x = 1 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}2. Checked Exceptions
Java's checked exceptions (those extending Exception but not RuntimeException) must be declared in the method signature with throws or caught explicitly.
# Python: no concept of checked exceptionsstatic void readFile(String path) throws IOException {
// compiler forces caller to handle IOException
}3. Multi-catch
Java 7+ allows catching multiple exception types in one catch block using |.
except (TypeError, ValueError) as e:
print(e)catch (IllegalArgumentException | NullPointerException e) {
System.out.println(e.getMessage());
}4. try-with-resources
Java try-with-resources automatically calls .close() on AutoCloseable objects — the equivalent of Python's with statement.
with open("file.txt") as f:
data = f.read()try (var reader = new BufferedReader(new FileReader("file.txt"))) {
String data = reader.readLine();
}Common Mistakes
When coming from Python, developers often make these mistakes:
- Python except → Java catch; Python allows multiple except, Java allows multiple catch
- Python has an else block (no exception); Java does not
- Java has checked exceptions that must be declared with throws in the method signature
Key Takeaways
- except → catch, same structure
- Checked exceptions must be declared with throws or caught
- try-with-resources ≈ Python with statement