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.")
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}")
- 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.”)
- 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!”)
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”)
- 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
- 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)
- 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))
Handling exceptions is important for several reasons:
A simple program error handling example:
try: result = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero.")
# 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}")
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!