Python Try-Except
When an exception occurs, and if we do not provide any checks or mechanisms to handle that exception, it can crash our Python application.
Python provides the try-except
block to handle errors gracefully, preventing the program from crashing due to exceptions.
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
When an error occurs in the try
block, Python jumps to the corresponding except
block to handle it instead of terminating execution.
How It Works
- The code inside the
try
block runs normally. - If an exception occurs, execution stops and jumps to the
except
block. - If an
ExceptionType
is specified, theexcept
block runs only for that specific type of exception. - The program does not crash and continues executing subsequent code.
Examples
1. Handling Division by Zero
We attempt to divide a number by zero, which raises a ZeroDivisionError
. Using try-except
, we handle this error gracefully.
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Output:
Error: Division by zero is not allowed.
Instead of crashing, Python executes the except
block and prints an error message.
2. Catching Multiple Exceptions
We can catch multiple exceptions using multiple except
blocks or by specifying multiple exception types in a single block.
try:
num = int("abc") # This will raise a ValueError
except ValueError:
print("Error: Invalid number format.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Output:
Error: Invalid number format.
Since int("abc")
raises a ValueError
, the corresponding except
block executes.
3. Using a Generic Exception
When we don’t know what kind of exception might occur, we can use a generic except
block without specifying an exception type.
try:
x = 1 / 0 # This raises ZeroDivisionError
except Exception as e:
print("An error occurred:", e)
Output:
An error occurred: division by zero
The Exception
class catches all types of exceptions, and the error message is displayed dynamically.
4. Using else
with try-except
The else
block executes only if no exceptions occur.
try:
num = int("10") # This will not cause an error
print("Conversion successful:", num)
except ValueError:
print("Error: Invalid input.")
else:
print("No exceptions occurred.")
Output:
Conversion successful: 10
No exceptions occurred.
Since there was no error, the else
block executes.
5. Using finally
Block
The finally
block executes regardless of whether an exception occurs or not.
try:
print("Trying to open a file...")
f = open("nonexistent.txt") # This will raise an error
except FileNotFoundError:
print("Error: File not found.")
finally:
print("Closing resources...")
Output:
Trying to open a file...
Error: File not found.
Closing resources...
The finally
block is always executed, making it useful for cleanup tasks like closing files or releasing memory.
6. Raising an Exception Using raise
We can manually raise exceptions using the raise
statement.
try:
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")
except ValueError as e:
print("Error:", e)
Output:
Error: Age cannot be negative!
By using raise
, we enforce constraints and prevent invalid data from being processed.