Python 3 — Exception Handling with try-except
Errors happen. A user might type invalid values, or your program might try to open a missing file. In professional software, a crash is unacceptable. Python provides exception handling structures to intercept errors and handle them gracefully.
An exception is a signal that an error has occurred during execution. Instead of continuing, Python halts program flow and raises a traceback detailing what went wrong. Standard exceptions include ZeroDivisionError, ValueError, and FileNotFoundError.
To prevent errors from crashing your script, isolate risky instructions in a try block. If an error is raised, Python skips the remaining try code and jumps to the matching except block:
try:
number = int(input("Enter a whole number: "))
result = 10 / number
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: You cannot divide a number by zero!")
except ValueError:
print("Error: That wasn't a valid whole number!")
You can append an optional finally block at the bottom. Code inside the finally block is guaranteed to run **no matter what**, whether an error occurred or not. This is commonly used for resource cleanup:
try:
print("Opening database...")
# Simulate an error
error_val = 10 / 0
except ZeroDivisionError:
print("Caught division by zero!")
finally:
print("Closing database connections safely!")
Writing except: without specifying the exception type (like except ValueError:) catches *every* error, including syntax slips or exit requests. This hides bugs and makes debugging extremely difficult. Always specify the specific exception you want to handle.
Write a calculator program that divides two numbers. Wrap the inputs and division calculations inside a 'try-except' block to cleanly handle inputs that aren't numeric, and division by zero.