As introduced, Python programs can encounter errors during execution, known as exceptions. When an exception occurs and isn't handled, the program typically stops and displays an error message (a traceback). This abrupt halt isn't ideal for users or for applications that need to remain stable.
To manage these situations, Python provides the try
and except
statements. This structure allows you to isolate code that might raise an exception and define specific actions to take if one does occur.
The fundamental syntax involves two blocks:
try
block: You place the code that you suspect might cause an exception inside this block. Python will attempt to execute this code normally.except
block: This block immediately follows the try
block. The code inside the except
block is executed only if an exception occurs within the preceding try
block. If the try
block completes without any exceptions, the except
block is skipped entirely.Here's how it looks in code:
try:
# Code that might raise an exception
# For example, getting user input and converting it
age_str = input("Please enter your age: ")
age = int(age_str)
print(f"Next year, you will be {age + 1}.")
except:
# Code to execute if *any* exception occurred in the try block
print("Something went wrong. Please enter a valid number for your age.")
print("Execution continues after the try-except block.")
Let's trace the execution flow with the example above:
try
block.try
code: It executes age_str = input(...)
. Let's say the user enters "30".try
code: It executes age = int(age_str)
. This works fine, converting "30" to the integer 30
.try
code: It executes print(...)
. This also works, printing "Next year, you will be 31.".try
block, the entire except
block is skipped.print("Execution continues...")
line after the try...except
structure.Now, consider what happens if the user enters "thirty" instead of "30":
try
block.try
code: It executes age_str = input(...)
. The variable age_str
now holds "thirty".try
code: It attempts to execute age = int(age_str)
. This fails because "thirty" cannot be converted directly into an integer. A ValueError
exception is raised at this point.try
block (the print(f"Next year...")
line is never reached).except
: Python looks for an except
block following the try
block. It finds one.except
code: The code inside the except
block is executed: print("Something went wrong...")
.except
block finishes, execution proceeds to the print("Execution continues...")
line after the try...except
structure.Notice the significant difference: instead of crashing with a ValueError
traceback, the program printed a helpful message and continued running. This is the core purpose of exception handling: to catch potential errors and respond to them gracefully.
except
The example above uses a bare except:
clause. This acts as a "catch-all" – it will handle any type of exception that occurs in the try
block, whether it's a ValueError
, a ZeroDivisionError
, a TypeError
, or something else entirely.
numerator = 10
denominator = 0
try:
result = numerator / denominator # This will cause a ZeroDivisionError
print("The result is:", result)
except:
print("An error occurred during division.")
print("Program finished.")
While simple, using a bare except:
is often not recommended in larger programs. Why? Because it can catch errors you didn't anticipate, potentially hiding bugs or making it harder to understand exactly what went wrong. If your try
block could raise several different kinds of errors, a generic except:
might handle them all in the same way, which might not be appropriate. It's usually better to handle specific types of exceptions, which we will look at next.
© 2025 ApX Machine Learning