Things go wrong at runtime — a file might not exist, user input might not be what was expected. Python's try/except handles this gracefully instead of crashing outright, with a couple of pieces worth knowing about specifically.
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
try:
print(divide(10, 0))
except ValueError as e:
print(f"Error: {e}")raise is how you trigger an exception yourself; except is what catches it.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Specifically caught: {e}")
except Exception as e:
print(f"General error: {e}")Order matters here — a specific exception type should come before a more general one that would otherwise catch it first.
Python also has an else block: it runs only if no exception was raised. finally runs either way, regardless of what happened above it:
try:
result = divide(10, 2)
except ValueError as e:
print(f"Error: {e}")
else:
print(f"Success: {result}") # only runs if no exception happened
finally:
print("Done.") # always runstry:
value = int("not a number")
except (ValueError, TypeError) as e:
print(f"Bad input: {e}")Writing except: with no type at all catches literally everything, including mistakes you'd actually want to see — a typo'd variable name, a missing import. It silently hides bugs instead of surfacing them:
# Avoid this — catches every possible error, including your own bugs:
try:
risky_operation()
except:
pass
# Prefer this — catches runtime problems, but a real code bug still surfaces:
try:
risky_operation()
except Exception as e:
print(f"Something went wrong: {e}")except Exception is about as broad as you should normally go — it still lets Python's own internal signals (like the one used by Ctrl+C) through, which a bare except: would swallow too.
Tracebacks are for developers, not users
An uncaught exception on a real, deployed Python program prints a full traceback — file paths, line numbers, sometimes variable values — which is invaluable for you while developing, but should never be shown directly to an end user. Wrapping risky operations (file access, network requests, user input parsing) in try/except is what turns that into a clean, controlled message instead.