Python Exception Handling
Exception handling in Python is used to handle errors gracefully without stopping the program. Python uses try, except, else, and finally blocks for this purpose.
try block:
The code that may cause an error is placed inside a try block.
Example:
try:
x = 10 / 0
except block:
Handles the exception if it occurs.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Catching multiple exceptions:
You can handle different exceptions in separate except blocks.
Example:
try:
x = int(input("Enter number: "))
y = 10 / x
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
Using a single except for multiple exceptions:
Example:
try:
x = int(input("Enter number: "))
y = 10 / x
except (ValueError, ZeroDivisionError):
print("Error occurred")
else block:
The else block runs if no exception occurs in the try block.
Example:
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", x)
finally block:
The finally block always executes, whether an exception occurs or not.
It is commonly used to close resources.
Example:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("Execution finished")
Raising exceptions manually:
Use raise to trigger an exception intentionally.
Example:
x = -5
if x < 0 data-start="1731" data-end="1734">
raise ValueError("Negative value not allowed")
Custom exceptions:
You can create custom exception classes by inheriting from the Exception class.
Example:
class MyError(Exception):
pass
x = 10
if x > 5:
raise MyError("x cannot be greater than 5")
Take quizzes related to this topic and see where you stand!
Start Quiz Now