Python try-except
In this page:
try:
# risky code
except ExceptionType as error:
# handle error
except (TypeA, TypeB):
# handle either
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) # no exception raised here
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): # handles either exception type the same way
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: # saves the exception object for inspection
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") # failure of the fallback itself
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: # catches ordinary errors but lets KeyboardInterrupt through
print("Caught ordinary errors, not KeyboardInterrupt:", e)
- Using a bare
except:that also catchesKeyboardInterrupt, so Ctrl+C no longer stops the program; catch specific exceptions. - Silencing errors with
except Exception: pass, which hides real bugs. - Putting too much code inside
try, so you cannot tell which line caused the caught error.
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: