GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Understanding Python Exceptions: Effective Error Handling Python Exceptionslast modified February 24, 2025
Exceptions in Python are events that occur during the execution of a program
that disrupt the normal flow of instructions. Python provides a robust mechanism
for handling exceptions using
Exceptions are errors that occur during the execution of a program. When an
exception occurs, Python creates an exception object and stops the program
unless the exception is handled. Common exceptions include
Handling Division by Zero
This example demonstrates how to handle a division by zero error using a
division_by_zero.py
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
The Handling Multiple Exceptions
This example demonstrates how to handle multiple exceptions using a single multiple_exceptions.py
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
The Using the Else Clause
This example demonstrates how to use the else_clause.py
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print(f"Result: {result}")
The Using the Finally Clause
This example demonstrates how to use the finally_clause.py
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")
The Raising Custom Exceptions
This example demonstrates how to raise custom exceptions using the custom_exception.py
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
elif age < 18:
raise ValueError("You must be at least 18 years old.")
else:
print("Access granted.")
try:
check_age(-5)
except ValueError as e:
print(f"Error: {e}")
The Creating Custom Exception Classes
This example demonstrates how to create custom exception classes by inheriting
from the custom_exception_class.py
class InvalidAgeError(Exception):
def __init__(self, message="Invalid age."):
self.message = message
super().__init__(self.message)
def check_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative.")
elif age < 18:
raise InvalidAgeError("You must be at least 18 years old.")
else:
print("Access granted.")
try:
check_age(-5)
except InvalidAgeError as e:
print(f"Error: {e}")
The Best Practices for Exception Handling
SourcePython Exceptions Documentation In this article, we have explored Python exceptions and demonstrated how to handle them effectively using practical examples. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |