Python Exception Handling
What is Exception Handling?
When an error occurs, Python stops execution and raises an exception. Exception handling lets you catch those errors and decide how to respond, so your program continues running or fails gracefully.
Basic Syntax
try:
# Code that might raise an exception
risky_code()
except SomeException:
# Code that runs if the exception occurs
handle_error()
Example: ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
You can't divide by zero!
Catching Multiple Exceptions
try:
num = int("abc")
result = 10 / 0
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Division by zero error!")
Output:
Invalid input!
Using else
The else
block runs if no exception occurs.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
Output:
Division successful: 5.0
Using finally
The finally
block always runs, whether an exception occurred or not.
try:
result = 10 / 0
except ZeroDivisionError:
print("Caught an error")
finally:
print("This runs no matter what")
Output:
Caught an error
This runs no matter what
Raising Exceptions Manually
You can use the raise
keyword to throw an exception.
x = -1
if x < 0:
raise ValueError("Negative values are not allowed")
Output:
ValueError: Negative values are not allowed
Custom Exception Class
class MyError(Exception):
pass
try:
raise MyError("Something went wrong")
except MyError as e:
print("Caught custom error:", e)
Summary Table
Block | Purpose |
---|---|
try | Code that might throw an error |
except | Code to run if an error occurs |
else | Code to run if no error occurs |
finally | Code that runs no matter what (cleanup, closing files) |