Intermediate·8 min·intermediate · errors
Errors & try/except
Errors & try/except
Python raises exceptions when something goes wrong. You can catch them.
The pattern
try:
risky()
except SomeError as e:
handle(e)
finally:
cleanup()
Best practices
- Catch the narrowest exception you can. Bare
except:hides real bugs. - Don't catch what you can't handle. Letting an error bubble up is often the right call.
- Use
finally:for cleanup that must run either way.
Try it
- Add a check for negative
band raise aValueError. - Wrap the calls in a
tryand print every error you get.