Python Try…Except
Python Try…Except
In Python, exceptions are errors that can disrupt the normal flow of a program. To handle these errors gracefully, Python provides the try...except block, which allows you to catch and manage exceptions without crashing the program.
Basic Syntax of Try…Except
try:
# Code that might raise an exception
risky_code()
except SomeException:
# Code to handle the exception
handle_error()
try: You write the code that you suspect might raise an exception here.except: You define how to handle the exception if it occurs.
Example 1: Basic Try…Except
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
You can't divide by zero!
Explanation:
In this example, the code inside the try block attempts to divide 10 by 0, which would normally raise a ZeroDivisionError. The except block catches the exception and prints a message.
Catching Multiple Exceptions
You can handle multiple exceptions by specifying multiple except blocks or by handling several exceptions in a single block.
Example 2: Multiple Except Blocks
try:
x = int(input("Enter a number: "))
y = 10 / x
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
Output (if the user inputs a non-numeric value):
That's not a valid number!
Example 3: Multiple Exceptions in One Block
try:
x = int(input("Enter a number: "))
y = 10 / x
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
Output (if the user inputs 0):
Error: division by zero
In this example, both ValueError and ZeroDivisionError are caught by the same except block. The as e part allows you to access the exception object and print the error message.
The Else Block
You can add an else block after all the except blocks. This block will run if no exceptions are raised in the try block.
Example 4: Using else
try:
x = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division was successful!")
Output:
Division was successful!
The Finally Block
You can also add a finally block. This block will always run, regardless of whether an exception occurred or not. It is often used for cleanup actions (e.g., closing files or network connections).
Example 5: Using finally
try:
file = open("myfile.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the file.")
file.close()
Output (if the file is not found):
File not found!
Closing the file.
Even if the file is not found and an exception is raised, the finally block is executed, ensuring the file is closed properly.
Raising Exceptions
In addition to catching exceptions, you can also raise exceptions explicitly using the raise keyword.
Example 6: Raising Exceptions
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero!")
return x / y
try:
result = divide(10, 0)
except ValueError as e:
print(f"Error: {e}")
Output:
Error: Cannot divide by zero!
Custom Exceptions
You can define your own exceptions by subclassing the built-in Exception class. This is useful when you want to raise and handle domain-specific errors.
Example 7: Custom Exception
class MyCustomError(Exception):
pass
try:
raise MyCustomError("Something went wrong!")
except MyCustomError as e:
print(f"Caught custom error: {e}")
Output:
Caught custom error: Something went wrong!
Best Practices
- Avoid Catching All Exceptions: It’s a good practice to specify which exceptions you expect to handle, rather than using a generic
exceptblock.try: # some code except Exception as e: # handle errorThis approach can hide errors that you didn’t anticipate.
- Use Finally for Cleanup: Always use the
finallyblock for cleanup tasks (e.g., closing files, releasing resources), since it is guaranteed to execute. - Minimal Try Block: Put only the code that might raise an exception inside the
tryblock. This helps make the exception handling more efficient and easier to debug. - Log Exceptions: Instead of just printing the error message, consider logging the exception details for later analysis. You can use the
loggingmodule to log errors in Python.
Conclusion
The try...except block is a powerful feature for handling exceptions in Python, allowing you to manage errors gracefully and ensure that your program continues running smoothly. You can catch multiple exceptions, add cleanup actions, and even create custom exceptions to meet your needs.