Python Try…Except
The try...except
statement in Python is used to handle exceptions or errors that may occur during the execution of a program. It allows you to catch and handle specific exceptions gracefully, preventing your program from crashing and providing a way to handle the error condition.
The basic syntax of the try...except
statement is as follows:
python
try:
# Code that may raise an exception
except ExceptionType1:
# Code to handle ExceptionType1
except ExceptionType2:
# Code to handle ExceptionType2
else:
# Code that runs if no exceptions were raised
finally:
# Code that always runs, regardless of whether an exception was raised or not
Here’s a breakdown of the various parts of the try...except
statement:
- The
try
block contains the code that might raise an exception. - The
except
block(s) define the exception(s) you want to catch and handle. If any of the specified exceptions occur within thetry
block, the correspondingexcept
block will be executed. You can have multipleexcept
blocks to handle different exception types. - The
else
block is optional and runs if no exceptions were raised in thetry
block. It is typically used for code that should execute only if no exceptions occurred. - The
finally
block is also optional and always runs, regardless of whether an exception occurred or not. It is often used for cleanup operations, such as closing files or releasing resources.
Here’s an example that demonstrates the usage of try...except
:
python
try:
x = 10 / 0 # This will raise a ZeroDivisionError
print("This line will not be executed.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No exceptions occurred.")
finally:
print("Finally block always runs, regardless of exceptions.")
In this example, a ZeroDivisionError
exception occurs when trying to divide 10 by 0. The except ZeroDivisionError
block catches the exception and executes the code inside it, printing the error message. Since an exception occurred, the else
block is skipped, and the finally
block is executed, printing the final message.
By using the try...except
statement, you can handle specific exceptions and gracefully handle error conditions in your code, making it more robust and preventing crashes.