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.

Worked 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?

Lesson test

Take an 8-question test on “Exceptions” — concepts, output prediction, bug spotting and interview questions.