Exception handling in Python helps manage errors gracefully without crashing the program. It uses the try, except, else, and finally blocks to catch and handle exceptions.
An exception is an error that occurs during execution, stopping the program.
| Exception | Cause |
|---|---|
ZeroDivisionError | Division by zero (5 / 0) |
TypeError | Invalid type operation ("5" + 5) |
ValueError | Incorrect value format (int("abc")) |
FileNotFoundError | Trying to open a non-existent file |
IndexError | Accessing an invalid index in a list |
KeyError | Accessing a non-existent key in a dictionary |
The try block runs the code, and if an error occurs, the except block executes.
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")If the user enters 0, ZeroDivisionError is handled.
If the user enters "abc", ValueError is handled.
You can handle multiple exceptions in a single except block.
try:
num = int(input("Enter a number: "))
result = 10 / num
except (ZeroDivisionError, ValueError) as e:
print("An error occurred:", e)as e stores the actual error message.
The else block runs if no exception occurs.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
else:
print("Successful! The result is:", result)If no exception occurs, the else block runs.
If an error occurs, the else block is skipped.
The finally block always executes, whether an exception occurs or not.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file (if opened).")
if 'file' in locals():
file.close()The finally block is useful for cleanup operations like closing files or releasing resources.
You can raise exceptions using raise.
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be at least 18 years old.")This manually triggers a ValueError if the user enters an age below 18.
Use try to test code that might cause an error.
Use except to handle specific errors.
Use else to execute code when no exception occurs.
Use finally to execute cleanup operations.
Use raise to manually trigger exceptions.
Sign in to join the discussion and post comments.
Sign inObject-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.
Python for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.