Exception Handling
Error handling patterns
Introduction
In this lesson, you'll learn about exception handling in Python. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with error handling patterns.
Python has its own approach to error handling patterns, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
# All exceptions are unchecked in Python
class NotFoundException(Exception):
def __init__(self, message: str):
super().__init__(message)
def find_user(user_id: int):
if user_id not in users:
raise NotFoundException(f"User {user_id} not found")
return users[user_id]
try:
u = find_user(42)
except NotFoundException as e:
print(f"Not found: {e}")
except Exception:
raise # bare raise preserves traceback
finally:
print("done")Comparing to Java
Here's how you might have written similar code in Java:
// Checked exception
public class NotFoundException extends Exception {
public NotFoundException(String msg) { super(msg); }
}
// Must declare or catch checked exceptions
public User findUser(int id) throws NotFoundException {
if (!users.containsKey(id))
throw new NotFoundException("User " + id + " not found");
return users.get(id);
}
try {
User u = findUser(42);
} catch (NotFoundException e) {
System.out.println("Not found: " + e.getMessage());
} catch (Exception e) {
throw e;
} finally {
System.out.println("done");
}You may be used to different syntax or behavior.
Python has no checked exceptions; Java forces you to declare or catch them
You may be used to different syntax or behavior.
Python 'except Type as e' = Java 'catch (Type e)'
You may be used to different syntax or behavior.
Python bare 'raise' = Java bare 'throw' to rethrow
You may be used to different syntax or behavior.
Python exception hierarchy: BaseException > Exception > specific
Step-by-Step Breakdown
1. No Checked Exceptions
Python has no checked exceptions. All exceptions extend Exception. No throws declaration needed on function signatures.
public void save() throws IOException { ... }def save(): # no throws needed
# just raise if something goes wrong2. except Syntax
Python's except clause is similar to Java's catch, but uses 'as' instead of the exception type before the variable.
catch (NotFoundException e) { e.getMessage() }except NotFoundException as e: str(e)3. Bare raise
Bare 'raise' in Python rethrows the current exception preserving the original traceback, like Java's bare 'throw'.
throw; // Java bare rethrowraise # Python bare rethrowCommon Mistakes
When coming from Java, developers often make these mistakes:
- Python has no checked exceptions; Java forces you to declare or catch them
- Python 'except Type as e' = Java 'catch (Type e)'
- Python bare 'raise' = Java bare 'throw' to rethrow
Key Takeaways
- Python has no checked exceptions
- except Type as e = catch (Type e)
- Bare raise = bare throw (preserves traceback)
- finally works identically