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, the same idea as PHP's try/catch, with a couple of extra pieces.
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 Python's equivalent of PHP's throw; except is the equivalent of catch.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Specifically caught: {e}")
except Exception as e:
print(f"General error: {e}")Just like PHP, order matters — a specific exception type should come before a more general one that would otherwise catch it first.
Python adds an else block PHP doesn't have: it runs only if no exception was raised. finally runs either way, exactly like PHP's:
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}")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.