Try-Except Blocks
Try-Except Blocks
The try-except block is Python's primary mechanism for handling errors. Code that might raise an exception is placed in the try block, and error handling code goes in the except block.
You can have multiple except blocks to handle different types of errors, and use else and finally for additional control flow.
Basic Try-Except
The basic structure catches all exceptions or specific exception types:
try_except.py
# Catch specific exception
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
# Catch all exceptions (not recommended for production)
try:
# Some code
pass
except Exception as e:
print(f"An error occurred: {e}")
Else and Finally
The else block runs if no exception occurs, and finally always runs:
else_finally.py
# Try-except-else
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered: {number}")
# This runs only if no exception occurred
# Try-except-finally
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Cleanup code here")
# This always runs, even if exception occurs
# Useful for closing files, cleaning up resources
Multiple Exceptions
You can catch multiple exceptions in a single except block:
multiple_exceptions.py
# Catch multiple exceptions
try:
# Some operation
pass
except (ValueError, TypeError, KeyError) as e:
print(f"Error occurred: {e}")
# Or handle separately
try:
# Some operation
pass
except ValueError:
print("Value error!")
except TypeError:
print("Type error!")
except Exception as e:
print(f"Other error: {e}")
Best Practices
✅ Try-Except Tips
• Be specific about which exceptions to catch
• Use finally for cleanup code (closing files, etc.)
• Use else for code that should run only if no exception
• Don't catch exceptions you can't handle
• Provide meaningful error messages
main.py
📤 Output
Click "Run" to execute...