Things go wrong in real programs — a user types text where a number is expected, a file doesn't exist, a network call times out. Without handling, any of these crashes your entire program with an unhandled error (a "traceback"). Python's try/except/finally structure lets you anticipate specific failures and respond to them gracefully instead of letting the whole program die.
Basic try / except
Code that might fail goes inside try. If an error occurs, Python jumps straight to the matching except block instead of crashing.
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("You can't divide by zero.")
except ValueError:
print("That wasn't a valid number.")
Output:
// Input: 0
You can't divide by zero.
// Input: abc
That wasn't a valid number.
Catching specific exception types like ZeroDivisionError or ValueError — rather than a bare except: that catches everything — is important: a bare except silently swallows bugs you probably want to know about, like a typo in a variable name.
else and finally
An else block runs only if the try block succeeded with no exception. A finally block always runs, whether an exception happened or not — commonly used for cleanup, like closing a file or a network connection.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Can't divide by zero.")
else:
print(f"Success: {result}")
finally:
print("Done attempting the calculation.")
Output:
// Input: 5
Success: 2.0
Done attempting the calculation.
Catching Multiple Exceptions in One Block
If several exception types should be handled the same way, group them in a tuple instead of repeating the handling code.
try:
data = {"a": 1}
value = data["b"] / 0
except (KeyError, ZeroDivisionError) as e:
print(f"Something went wrong: {type(e).__name__}")
Output:
Something went wrong: KeyError
Once you're comfortable with Python's built-in exceptions, the natural next step is defining your own custom exceptions for errors specific to your application. You can also see a complete worked example with multiple except blocks in the exception handling program example.
