Handling Exceptions with Python

Introduction to Exceptions

Exceptions are events that occur during the execution of a program that disrupt the normal flow of control. In Python, exceptions are represented by objects and provide a structured way to handle errors.

Types of Exceptions

Python has several built-in exception types. Here are some of the most common:

  • Exception: The base class for all exceptions.
  • ZeroDivisionError: Raised when a division by zero is attempted.
  • FileNotFoundError: Raised when a file operation fails because the file was not found.
  • ValueError: Raised when a function receives an argument of the correct type but inappropriate value.
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.

Handling Exceptions with try and except

The try block contains code that might raise an exception. If an exception occurs, the except block catches it and allows for error handling.

Example: Division 

try:
    numerator = int(input("Enter the numerator: "))
    denominator = int(input("Enter the denominator: "))
    result = numerator / denominator
except ZeroDivisionError:
    print("Error: Division by zero.")
except ValueError:
    print("Error: Invalid input. Please enter integer values.")
else:
    print(f"Result: {result}")
finally:
    print("End of processing.")

In this example:

  • try: Contains code that might generate exceptions.
  • except ZeroDivisionError: Catches division-by-zero errors.
  • except ValueError: Catches errors related to invalid input.
  • else: Executes if no exceptions were raised.
  • finally: Executes regardless of whether an exception was raised or not, often used for cleanup tasks.

Raising Exceptions with raise

You can manually raise exceptions using the raise statement. This is useful for signaling errors in your own functions or methods.

Example: Validation Function 

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return f"Age is {age}."
try:
    age = int(input("Enter your age: "))
    print(check_age(age))
except ValueError as e:
    print(f"Error: {e}")

Catching Multiple Exceptions

You can catch multiple exceptions by listing them in a single except clause, or by using multiple except clauses.

Example: 

try:
    value = int(input("Enter a number: "))
    result = 10 / value
except (ZeroDivisionError, ValueError) as e:
    print(f"Error: {e}")

Creating Custom Exceptions

You can create your own exception classes by inheriting from the Exception class. This allows you to define exceptions specific to your application.

Example: Custom Exception 

class CustomError(Exception):
    def __init__(self, message):
        super().__init__(message)
def risky_function():
    raise CustomError("A custom error occurred.")
try:
    risky_function()
except CustomError as e:
    print(f"Custom error: {e}")

Conclusion

Error handling in Python is crucial for writing robust and reliable code. By using try, except, else, and finally blocks, you can handle errors gracefully. Raising exceptions with raise and creating custom exceptions further allows for precise error signaling.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *