Exception handling in Python
During program execution, unexpected situations may occur: division by zero, access to a non-existent file, incorrect user input, or network connection failures. Such situations are called exceptions. Python provides a powerful and flexible exception handling mechanism that allows developers to prevent program crashes and properly respond to errors.
What Is an Exception?
An exception is an object that describes an error occurring during program execution. When an exception occurs, the normal flow of the program is interrupted.
print(10 / 0)
This code produces a ZeroDivisionError because division by zero is mathematically impossible.
The try-except Block
The primary mechanism for handling exceptions in Python is the try-except block. Code that may cause an error is placed inside the try block, while the error handling logic is placed inside the except block.
try:
number = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
If an exception occurs inside the try block, Python immediately transfers execution to the corresponding except block.
Handling Multiple Exceptions
A program may encounter different types of errors. Python allows handling multiple exceptions separately.
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid number format.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
This approach makes programs more reliable and user-friendly.
The finally Block
The finally block contains code that will always execute, regardless of whether an exception occurred.
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found.")
finally:
print("Program execution completed.")
The finally block is often used to release resources such as files, database connections, or network sockets.
The else Block
Python also supports the else block, which executes only if no exception occurs.
try:
result = 10 / 2
except ZeroDivisionError:
print("Error.")
else:
print("Calculation successful:", result)
This improves code readability by separating successful execution logic from error handling logic.
Accessing Exception Information
Exception objects may contain detailed information about the error. This information can be accessed using the as keyword.
try:
number = int("abc")
except ValueError as error:
print("An error occurred:", error)
This is useful for debugging and logging.
Raising Exceptions
Python allows developers to explicitly generate exceptions using the raise statement.
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
This mechanism helps enforce program constraints and validate input data.
Custom Exceptions
Developers can create their own exception classes by inheriting from the built-in Exception class.
class InvalidPasswordError(Exception):
pass
password = "123"
if len(password) < 6:
raise InvalidPasswordError("Password is too short.")
Custom exceptions make large projects easier to maintain and improve code clarity.
Common Built-in Exceptions
Python provides many built-in exception types. Some of the most common include:
ZeroDivisionError — division by zero.
ValueError — invalid value type or format.
TypeError — operation applied to an incompatible type.
FileNotFoundError — requested file does not exist.
IndexError — invalid list index.
KeyError — missing dictionary key.
Best Practices
Exception handling should be used carefully. It is recommended to catch only specific exceptions instead of using broad handlers such as except:, because overly generic handling may hide programming errors.
try:
value = int(input())
except ValueError:
print("Please enter a valid integer.")
Clear and informative error messages significantly improve user experience and simplify debugging.
Exception handling is an essential part of reliable software development in Python. The language provides convenient tools for detecting, processing, and generating exceptions, allowing programs to remain stable even in unexpected situations. Understanding exception handling mechanisms helps developers create more robust, maintainable, and user-friendly applications.
Original: www.webjdev.com
Comments
Post a Comment