try and except
Handle an error instead of crashing. Code in try runs; if it raises the named error, except runs.
Syntax
try:...except ValueError:...
- Name the error you expect. A bare except hides real bugs.
Example
try:
int("abc")
except ValueError:
print("not a number")Output:
not a number
Common mistakes
- Catching everything with except: makes bugs invisible.
- Keep the try block small, so you know which line failed.