Free Coding Tutorials: Mastering Python Fundamentals – Part 8

Delphi

Chapter 8: Exception Handling

Exception handling, in Mastering Python Fundamentals, is an important concept in programming, allowing you to manage errors gracefully. Python provides a robust mechanism to catch and handle exceptions, ensuring that your programs can continue running even when something goes wrong. In this chapter, we’ll explore how to handle exceptions in Python with step-by-step instructions and examples.

8.1 Understanding Exceptions

Exceptions are errors that occur during the execution of a program. When an error occurs, Python raises an exception, which can stop the program unless it’s handled properly.

8.1.1 Common Types of Exceptions

Here are some common exceptions in Python:

  • SyntaxError: Raised when there’s a syntax error in the code.
  • TypeError: Raised when an operation or function is applied to an object of an inappropriate type.
  • IndexError: Raised when trying to access an element of a list or tuple with an invalid index.
  • KeyError: Raised when trying to access a dictionary with a key that doesn’t exist.
  • FileNotFoundError: Raised when trying to open a file that doesn’t exist.

Example: Unhandled Exception

# Attempt to divide by zero
result = 10 / 0

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as unhandled_exception.py.
  4. Run the program by typing:
   python unhandled_exception.py
  1. Python will raise a ZeroDivisionError and stop the execution, displaying an error message.

8.2 The try...except Block

The try...except block is used to catch and handle exceptions. The code that might raise an exception is placed in the try block, and the code to handle the exception is placed in the except block.

8.2.1 Basic Exception Handling

You can catch specific exceptions using the try...except block.

Example: Handling Division by Zero

try:
    # Attempt to divide by zero
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as handle_division_by_zero.py.
  4. Run the program by typing:
   python handle_division_by_zero.py
  1. The output will display Error: Division by zero is not allowed. instead of stopping the program.

8.2.2 Catching Multiple Exceptions

You can catch multiple exceptions using multiple except blocks or a single except block with a tuple of exceptions.

Example: Handling Multiple Exceptions

try:
    # Attempt to open a file and divide by zero
    file = open('non_existent_file.txt', 'r')
    result = 10 / 0
except FileNotFoundError:
    print("Error: The file was not found.")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as handle_multiple_exceptions.py.
  4. Run the program by typing:
   python handle_multiple_exceptions.py
  1. The output will display Error: The file was not found. since the file doesn’t exist.

8.2.3 Using a Single except Block for Multiple Exceptions

You can also handle multiple exceptions in a single except block.

Example: Single except Block

try:
    # Attempt to open a file and divide by zero
    file = open('non_existent_file.txt', 'r')
    result = 10 / 0
except (FileNotFoundError, ZeroDivisionError) as e:
    print(f"Error: {e}")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as single_except_block.py.
  4. Run the program by typing:
   python single_except_block.py
  1. The output will display Error: [Errno 2] No such file or directory: 'non_existent_file.txt'.

8.3 The else Clause

The else clause can be used to define a block of code to be executed if no exceptions are raised in the try block.

Example: Using else Clause

try:
    # Attempt to divide two numbers
    result = 10 / 2
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
else:
    print(f"The result is {result}.")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as else_clause.py.
  4. Run the program by typing:
   python else_clause.py
  1. The output will display The result is 5.0. since no exception was raised.

8.4 The finally Clause

The finally clause is used to define a block of code that will be executed regardless of whether an exception is raised or not. This is useful for cleaning up resources like closing files or network connections.

Example: Using finally Clause

try:
    # Attempt to open a file
    file = open('example.txt', 'r')
except FileNotFoundError:
    print("Error: The file was not found.")
finally:
    print("This block is executed no matter what.")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as finally_clause.py.
  4. Run the program by typing:
   python finally_clause.py
  1. The output will display:
   Error: The file was not found.
   This block is executed no matter what.

8.5 Raising Exceptions

Sometimes, you may want to raise an exception intentionally using the raise statement.

Example: Raising an Exception

def check_age(age):
    if age < 18:
        raise ValueError("Age must be at least 18.")
    return "Access granted."

# Attempt to check age
try:
    print(check_age(16))
except ValueError as e:
    print(f"Error: {e}")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as raise_exception.py.
  4. Run the program by typing:
   python raise_exception.py
  1. The output will display Error: Age must be at least 18.

8.6 Custom Exceptions

You can create custom exceptions by defining a new class that inherits from the built-in Exception class. This is useful when you need to create specific error types for your application.

Example: Creating a Custom Exception

class CustomError(Exception):
    def __init__(self, message):
        self.message = message

def risky_function(value):
    if value < 0:
        raise CustomError("Negative value error.")
    return "Value is positive."

# Attempt to call the function
try:
    print(risky_function(-1))
except CustomError as e:
    print(f"Error: {e.message}")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as custom_exception.py.
  4. Run the program by typing:
   python custom_exception.py
  1. The output will display Error: Negative value error.

Conclusion

Exception handling is a powerful feature in Python that helps you manage errors gracefully and keep your programs running smoothly. By mastering exception handling techniques, you can create more robust and error-resistant applications. This chapter provided a comprehensive overview, from basic exception handling to creating custom exceptions, with practical examples and detailed instructions. Happy coding!

Latest Posts