Python try...except
Exception Handling in Python
In Python, the try...except statement is used for exception handling. It allows you to catch and handle exceptions that might occur during the execution of a block of code. This helps in preventing your program from crashing when unexpected errors occur.
Basic Syntax:
try:
# Code that may raise an exception
# ...
except ExceptionType1 as variable1:
# Code to handle ExceptionType1
# ...
except ExceptionType2 as variable2:
# Code to handle ExceptionType2
# ...
else:
# Code that will be executed if no exception occurs
# ...
finally:
# Code that will be executed no matter what (optional)
# ...
- The
tryblock contains the code that may raise an exception. - The
exceptblock(s) specify the type of exception to catch and handle. You can have multipleexceptblocks to handle different types of exceptions. - The
elseblock contains code that will be executed if no exception occurs in thetryblock. It is optional. - The
finallyblock contains code that will be executed no matter what, whether an exception is raised or not. It is optional.
Example:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError as ve:
print(f"Error: {ve}. Please enter a valid integer.")
except ZeroDivisionError as zde:
print(f"Error: {zde}. Cannot divide by zero.")
else:
print("No exception occurred.")
finally:
print("This will be executed no matter what.")
In this example, the program attempts to perform division based on user input. It catches ValueError if the user does not enter a valid integer and ZeroDivisionError if the user tries to divide by zero. The else block prints a message if no exception occurs, and the finally block prints a message that will be executed regardless of whether an exception occurred or not.
Using try...except is a good practice for handling potential errors and ensuring that your program can gracefully handle unexpected situations. It helps improve the robustness of your code.