Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Best Practices for Exception Handling | Mastering Error Handling in Python
Python Advanced Concepts

book
Best Practices for Exception Handling

The 'as' Keyword in Exceptions

The as keyword is used in exception handling to capture an instance of the exception. This is useful for obtaining more details about the error and can be particularly helpful for logging or responding to the error in a more informed way.

try:
x = 10 / 0
except ZeroDivisionError as e:
print(f"Caught an exception: {e}")
1234
try: x = 10 / 0 except ZeroDivisionError as e: print(f"Caught an exception: {e}")
copy

What is Traceback?

A traceback provides details about the actual path taken by the execution of a program up to the point where the exception occurred. It includes the function calls made in your program and the line numbers in your code files where these calls were made. Tracebacks are vital for debugging errors in development and production environments.

Traceback (most recent call last):
File "example.py", line 7, in <module>
main()
File "example.py", line 4, in main
divide_by_zero()
File "example.py", line 2, in divide_by_zero
return 1 / 0
ZeroDivisionError: division by zero

Good Practices in Exception Handling

1. Catching Too General Exceptions

python
# Bad Practice
try:
process_data(data)
except Exception:
pass

# Best Practice
try:
process_data(data)
except SpecificError:
handle_error()

Catching too general exceptions can obscure the root cause of errors, making debugging difficult and potentially masking other issues that require specific handling, thereby reducing the reliability and maintainability of the software.

2. Catch and Re-Raise Exception

If you need to perform an operation when an exception occurs but still want the exception to bubble up.

python
# Best Practice
try:
do_something()
except Exception as e:
log_error(e)
raise # Better: Re-raises the current exception

Note

The functions log_error(e) and print(e) both display the full traceback of an error, which can be helpful during development. However, in a production environment, showing complete tracebacks can expose the application to vulnerabilities, as they often contain sensitive information.

3. Exception Performance

Avoid overusing try-except blocks in your code, as excessive use can slow down your program. Only implement them when they serve a functional purpose. Using an if statement is generally faster and more efficient.

Compito

Swipe to start coding

Refactor the following Python script to improve its exception handling based on the best practices discussed.

python
def process_data(data):
try:
return data[0] / data[-1]
except:
print("An error occurred.")

# Example usage
result = process_data([1, 2, 0])
  • The code includes a check to ensure the data list is not empty before proceeding, using a ValueError.
  • The refactored code catches specific exceptions (ZeroDivisionError, TypeError, IndexError) instead of using a blanket except clause.
  • Each exception type has a custom error message that provides more context about what went wrong.

Soluzione

def process_data(data):
if not data:
raise ValueError("Data list cannot be empty.")
try:
result = data[0] / data[-1]
except ZeroDivisionError:
print("Cannot divide by zero in the data.")
except TypeError:
print("Data should contain only numbers.")
except IndexError:
print("Data list is too short.")
else:
print(f"Result: {result}")
finally:
print("Data processing attempted.")

# Example usage
result = process_data([1, 2, 0])

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 5
single

single

def process_data(data):
if not data:
___ ValueError("Data list cannot be empty.")
___:
result = data[0] / data[-1]
___ ZeroDivisionError:
print("Cannot divide by zero in the data.")
___ TypeError:
print("Data should contain only numbers.")
___ IndexError:
print("Data list is too short.")
___:
print(f"Result: {result}")
____:
print("Data processing attempted.")

# Example usage
result = process_data([1, 2, 0])

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt