Python Exception Handling

In this tutorial, you will learn about Exception handling In Python

Introduction


Exception handling is a crucial aspect of writing robust and error-resistant Python programs.

Inevitably, unexpected situations may arise during program execution, such as dividing by zero, accessing an undefined variable, or opening a non-existent file.

Python's exception handling mechanism allows developers to anticipate and gracefully handle such situations, preventing the program from crashing and providing meaningful feedback to users.

In this tutorial, we will explore the fundamentals of Python exception handling, covering concepts like try-except blocks, raising exceptions, handling multiple exceptions, and creating custom exceptions.

 

1. Understanding Exceptions


In Python, an exception is a runtime error that occurs during the execution of a program.

When an exception occurs, the program stops executing, and Python raises an exception object.

To handle these exceptions, Python provides a mechanism using the try, except, else, and finally blocks.

 

2. Basic Exception Handling with try and except


The try block is used to enclose the code that might raise an exception. The except block is used to handle the exception gracefully.

try:
    # code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

In this example, if a ZeroDivisionError occurs, the program will print an error message instead of crashing.

 

3. Handling Multiple Exceptions


You can handle multiple exceptions by specifying multiple except blocks.

try:
    # code that might raise an exception
    value = int(input("Enter a number: "))
    result = 10 / value
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Here, we handle both ValueError and ZeroDivisionError separately.

 

4. The else Block


The else block is executed if no exceptions are raised in the try block.

try:
    # code that might raise an exception
    value = int(input("Enter a number: "))
    result = 10 / value
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Result:", result)

The else block is useful for code that should only run when no exceptions occur.

 

5. The finally Block


The finally block contains code that will be executed no matter what, whether an exception occurs or not.

try:
    # code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This code always runs.")

The finally block is commonly used for cleanup operations.

 

6. Raising Exceptions


You can manually raise exceptions using the raise keyword. This is useful for signaling errors in your code.

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

In this example, if a negative age is provided, a ValueError is raised with a custom error message.

 

7. Creating Custom Exceptions


Developers can create their own custom exceptions by creating a new class that inherits from the Exception class.

class CustomError(Exception):
    def __init__(self, message="A custom error occurred"):
        self.message = message
        super().__init__(self.message)

# Using the custom exception
try:
    raise CustomError("This is a custom exception")
except CustomError as ce:
    print(ce)

Custom exceptions allow for more specific error handling within your application.

 

Summary


Exception handling is a crucial aspect of writing reliable and maintainable Python code. Understanding how to use try, except, else, and finally blocks, along with raising and creating custom exceptions, empowers developers to build robust applications that gracefully handle unexpected situations.

In the next chapter, we will explore advanced topics such as exception chaining, context managers, and best practices in exception handling.
 

© 2022-2023 All rights reserved.