Home > Backend Development > Python Tutorial > Exception Handling in Python

Exception Handling in Python

Mary-Kate Olsen
Release: 2024-12-06 20:19:12
Original
773 people have browsed it

Exception Handling in Python

This article explores the various techniques used to handle exceptions in Python, including try-except blocks, custom exceptions, and advanced features like exception chaining and enrichment.


Python provides a robust exception-handling framework that not only allows programmers to implement code that prevents crashes but also offers feedback and maintains application stability. Moreover, it enables developers to manage errors gracefully using constructs like try-except blocks, custom exceptions, and more.

- The Try-Except Block

In the try-except block, the code that may raise an exception is placed in the try-block, and the except-block specifies the actions to take if an exception occurs (Python Software Foundation, n.d.).

For example:

try:
    result = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
Copy after login
Copy after login

To catch multiple exceptions in one try-except block, we can use a try-block with several except-blocks to generate specific responses for each exception type. Or, we can use a tuple to catch multiple exceptions with a single exception expression.

For example:

# One try block and several except blocks
try:
    result = 1 / 'a'
except ZeroDivisionError:
    print("Cannot divide by zero.")
except TypeError:
    print("Type error occurred.")

# One try block and one except tuple block
try:
    # some operation
    result = 1 / 'a'
except (ZeroDivisionError, TypeError) as e:
    print(f"Error occurred: {e}")
Copy after login
Copy after login

- The Else Clause

The else clause, is placed after the try-except blocks and runs if the try block does not raise an exception.

For example:

try:
    result = 1 / 2
except ZeroDivisionError:
    print(“Cannot divide by zero.”)
else:
    print(“Division successful.”)
Copy after login

- The Finally Clause

The finally clause is always placed after the try-block or any except-block. It contains code that runs no matter what, typically for cleaning up resources like files or network connections, even if an exception was raised.

For example:

try:
    result = 1 / ‘a’
except ZeroDivisionError:
    print(“Cannot divide by zero.”)
except TypeError:
    print(“Type error occurred.”)
else:
    print(“Division successful.”)
finally:
    print(“Goodbye, world!”)
Copy after login
  • The Raise Statement

Raising exceptions: the raise clause raises exceptions by forcing an exception to occur, usually to indicate that a certain condition has not been met.

For example:

if ‘a’ > 5:
    raise ValueError(“A must not exceed 5”)
Copy after login

- Exception Chaining

You can chain exceptions with the clause raise. This is useful for adding context to an original error.

For Example

try:
    open(‘myfile.txt’)
except FileNotFoundError as e:
    raise RuntimeError(“Failed to open file”) from e
Copy after login

- Custom exceptions

You can define your own exception classes by inheriting from the Exception class or any other built-in exception class (Mitchell, 2022).

For example:

class My_custom_ (Exception):
    pass

try:
    raise MyCustomError(“An error occurred”)
except MyCustomError as e:
    print(e)
Copy after login

- Enriching exceptions

you can add information or context to an exception by using the add_note() method to ‘append’ custom messages or notes to the exception object aka e.

For example:

def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError as e:
        e.add_note(“Cannot divide by zero”)
        e.add_note(“Please provide a non-zero divisor”)
        raise
try:
    num1 = 10
    num2 = 0
    divide_numbers(num1, num2)
except ZeroDivisionError as e:
    print(“An error occurred:”)
    print(str(e))
Copy after login

Handling exceptions is important for several reasons:

  1. Prevents program crashes: Unhandled exceptions can cause the program to crash, leading to data loss and a poor user experience.
  2. Provides meaningful error messages: By handling exceptions, you can provide users with informative error messages that help them understand what went wrong and how to fix it.
  3. Allows for graceful degradation: Exception handling enables the program to continue running even if an error occurs.

A simple program error handling example:

try:
    result = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
Copy after login
Copy after login
# One try block and several except blocks
try:
    result = 1 / 'a'
except ZeroDivisionError:
    print("Cannot divide by zero.")
except TypeError:
    print("Type error occurred.")

# One try block and one except tuple block
try:
    # some operation
    result = 1 / 'a'
except (ZeroDivisionError, TypeError) as e:
    print(f"Error occurred: {e}")
Copy after login
Copy after login

To summarize, Python provides a comprehensive exception-handling framework that allows programs to handle unexpected situations without failing abruptly. By utilizing constructs such as try-except blocks, custom exceptions, and advanced features like exception chaining and enrichment, developers can ensure that their programs are resilient, user-friendly, and capable of handling unexpected scenarios gracefully.


References:

Mitchell R (2022, June 13). Custom exceptions. _Python Essential Training _[VIDEO]. LinkedIn Learning. https://www.linkedin.com/learning/python-essential-training-14898805/custom-exceptions?autoSkip=true&resume=false&u=2245842

Python Software Foundation. (n.d.). 8. Errors and Exceptions. Python. python.org.


Originally published at Exception Handling in Python - Medium on August 21, 2024.

The above is the detailed content of Exception Handling in Python. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template