L4Β·OOP & Errors

🚨Exceptions

try/except/else/finally and custom errors.

tryexceptraisecustom

Β§ 1try / except

Catch specific exception types. Bare except: catches everything (avoid).

Β§ 2else / finally

else runs if no exception. finally always runs β€” great for cleanup.

Β§ 3Raising

raise ValueError('bad input'). Custom exceptions inherit from Exception.

Example

1def parse_int(s):​
2 try:​
3 return int(s)​
4 except ValueError as e:​
5 print(f"can't parse {s!r}: {e}")​
6 return None​
7 finally:​
8 print("done")​
9​
10print(parse_int("42"))​
11print(parse_int("oops"))​

Try it live Β· Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
When does finally run?