Python try-except
In this page:
The try-except Block
The code inside a try block runs first, and if any statement in it raises an exception, execution jumps immediately to the matching except block instead of continuing -- if no exception occurs, the except block is simply skipped entirely.
Example: The try-except Block
try:
print(10 / 2)
except ZeroDivisionError:
print("This does not run")
Handling Multiple Exceptions
Writing several except clauses lets you handle different error types differently (a missing file vs. bad data need different fixes), or you can group related exception types into a single except (ValueError, TypeError): block when they should be handled the same way.
Example: Handling Multiple Exceptions
try:
int("abc")
except (ValueError, TypeError):
print("Caught ValueError or TypeError")
Catching Exception as Variable
'except ValueError as e:' saves the exception object to a variable so you can inspect its actual message with str(e), which is far more useful for logging or debugging than just knowing 'a ValueError happened somewhere'.
Example: Catching Exception as Variable
try:
int("abc")
except ValueError as e:
print(str(e))
Nested try-except Blocks
Placing a try/except inside another try/except lets you attempt a fallback recovery action and still catch failures in that recovery itself -- useful for something like 'try the primary server, and if reaching it fails, try a backup server, and handle failure of that too'.
Example: Nested try-except Blocks
try:
try:
raise ConnectionError("primary server down")
except ConnectionError:
raise ConnectionError("backup server also down")
except ConnectionError as e:
print(e)
Avoiding Bare except
A bare 'except:' with no exception type catches literally everything, including things like KeyboardInterrupt that a user might trigger intentionally to stop the program -- catching 'except Exception:' instead still catches ordinary errors but lets those system-level signals through.
Example: Avoiding Bare except
try:
int("abc")
except Exception as e:
print("Caught ordinary errors, not KeyboardInterrupt:", e)
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: