try / except
Catches errors so the program doesn't crash.
Syntax
try:
...
except Error:
...Description
You put risky code inside try; if an error occurs the except block runs and the program continues. finally runs in every case.
Example
Loading editor…
Expected output
Cannot divide by zero
When to use?
Preventing a crash when the user enters bad data, a file is missing, or the network drops.
Common mistakes
- ⚠️ A bare 'except:' hides every error; if possible, specify the error type.