Error Handling
Catching and throwing exceptions
Introduction
In this lesson, you'll learn about error handling in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with catching and throwing exceptions.
Python has its own approach to catching and throwing exceptions, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
import json
# try / except / else / finally
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Bad JSON: {e}")
except Exception as e:
raise # re-raise the same exception
else:
print("Parsed OK:", data) # runs if no exception
finally:
print("Always runs")
# Custom exception
class ValidationError(Exception):
def __init__(self, field, msg):
super().__init__(msg)
self.field = field
raise ValidationError("email", "Invalid email")Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// try / catch / finally
try {
const data = JSON.parse(badJson);
} catch (err) {
if (err instanceof SyntaxError) {
console.error("Bad JSON:", err.message);
} else {
throw err; // re-throw unknown errors
}
} finally {
console.log("Always runs");
}
// Custom error
class ValidationError extends Error {
constructor(field, msg) {
super(msg);
this.name = "ValidationError";
this.field = field;
}
}
throw new ValidationError("email", "Invalid email");You may be used to different syntax or behavior.
except instead of catch, multiple except blocks allowed
You may be used to different syntax or behavior.
else block runs when no exception occurred
You may be used to different syntax or behavior.
raise (no argument) re-raises the current exception
You may be used to different syntax or behavior.
Exceptions inherit from Exception, not Error
Step-by-Step Breakdown
1. Basic try/except
Python allows multiple except blocks for different error types.
try { ... } catch (err) { ... }try:
...
except ValueError:
...
except TypeError:
...2. The else Block
The else block only runs when no exception was raised — useful for code that should only run on success.
// No direct equivalent — must use a flagtry:
result = do_thing()
except SomeError:
handle()
else:
use(result) # only if no error3. Re-raising Exceptions
bare raise re-raises the current exception preserving its traceback.
throw err; // re-throw with same stackraise # re-raise current exception (same traceback)Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- except instead of catch, multiple except blocks allowed
- else block runs when no exception occurred
- raise (no argument) re-raises the current exception
Key Takeaways
- except replaces catch, multiple types supported
- else runs on success, finally always runs
- bare raise to re-raise without losing traceback