Handling Exceptions with try and except
When Python encounters a runtime error, it raises an exception and halts the program. To prevent this sudden crash and allow our program to handle the issue gracefully, we use the try and except blocks.
Think of the try block as your experimental zone and the except block as your safety zone.
How try-except Works
The basic syntax of a try-except block is as follows:
try:
# Code that might cause an error
pass
except:
# Code that runs only if an error happens in the try block
pass
Visualizing the Flow of Execution
-
Scenario A: No Error Occurs
- Python runs the code inside the
tryblock from start to finish. - Python skips the
exceptblock completely. - The program continues running the remaining code below the blocks.
- Python runs the code inside the
-
Scenario B: An Error Occurs
- Python runs the code inside the
tryblock until it hits a line with an error. - Python immediately stops executing the rest of the
tryblock. - Python jumps directly to the
exceptblock and runs the code inside it. - The program does not crash; it continues running the remaining code below.
- Python runs the code inside the
Why You Should Catch Specific Exceptions
While you can write a generic except: block that catches every error, it is a bad practice. Catching everything makes it hard to debug because you will not know what went wrong.
Instead, you should catch specific exceptions (like ZeroDivisionError or ValueError) so you can handle each problem appropriately.
Beginner-Friendly Example: A Safe Calculator
Let us write a program that takes two numbers from the user and divides them. We will handle two potential errors:
- The user entering text instead of a number (
ValueError). - The user trying to divide by zero (
ZeroDivisionError).
try:
# Get inputs and convert to integers
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
# Perform division
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
# Runs only if num2 is 0
print("Error: You cannot divide a number by zero.")
except ValueError:
# Runs only if user enters text instead of digits
print("Error: Please enter numbers only. Text is not allowed.")
except Exception as e:
# Runs for any other unexpected error (acts as a backup)
print(f"An unexpected error occurred: {e}")
print("Program continues running...")
Accessing the Error Message (as e)
Sometimes you want to see the actual error message generated by Python without crashing the program. You can capture the exception object using the as keyword:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Captured Error Message: {e}")
Output:
Captured Error Message: division by zero
Practical Examples for Beginners
Example 1: Safe File Reader
If we try to open a file that does not exist, the program normally crashes. Let us handle it:
try:
with open("config.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("Error: The 'config.txt' file was not found. Using default settings instead.")
Example 2: Safe Dictionary Lookup
If we try to look up a key that does not exist in a dictionary, Python raises a KeyError.
user_profile = {"username": "sai_coder", "email": "sai@example.com"}
try:
# Accessing a key that might not be there
print(user_profile["phone"])
except KeyError:
print("Warning: Phone number is not set in user profile.")