Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Best Practices for Error Handling | Custom Exceptions and Best Practices
Python Error Handling

bookBest Practices for Error Handling

Best Practices for Error Handling in Python

Follow these guidelines to write clear, maintainable, and safe error handling code:

  • Catch specific exceptions, such as ValueError or KeyError, instead of using a generic except: clause;
  • Avoid bare except: blocks, as they can mask unexpected problems and make debugging more difficult;
  • Use logging to record exceptions, which helps with monitoring and troubleshooting, rather than simply printing errors or ignoring them;
  • Do not suppress errors silently—always handle exceptions in a way that makes failures visible and traceable.
12345678910111213
import logging logging.basicConfig(level=logging.ERROR, filename='app.log') def divide(a, b): try: return a / b except ZeroDivisionError as e: logging.error("Division by zero attempted: %s", e) # Do not print or ignore the exception return None result = divide(5, 0)
copy

When to Re-raise Exceptions and Document Error Handling

You should re-raise an exception when you need to take some action—such as logging, cleaning up resources, or adding context—but still want the exception to propagate. This ensures that critical errors are not hidden and can be handled at a higher level in your application. Use the raise statement without arguments to re-raise the current exception after your handling logic.

Example Situations to re-raise Exceptions:

  • Logging the error before letting it propagate;
  • Cleaning up files or connections before re-raising;
  • Adding additional context to the error message, then re-raising.

Documenting Error Handling in your Code:

  • Use comments to explain why exceptions are caught or re-raised in complex blocks;
  • Add docstrings to functions and methods that describe which exceptions might be raised or handled;
  • Clearly state any side effects or cleanup actions performed during exception handling.

Sample Docstring:

def read_file(path):
    """
    Reads the contents of a file at the given path.
    Raises:
        FileNotFoundError: If the file does not exist.
        PermissionError: If the file cannot be accessed due to permissions.
    """
    # Error handling logic here

Clear documentation and thoughtful re-raising of exceptions help others understand your code, prevent silent failures, and make maintenance safer and more predictable.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Awesome!

Completion rate improved to 6.67

bookBest Practices for Error Handling

Sveip for å vise menyen

Best Practices for Error Handling in Python

Follow these guidelines to write clear, maintainable, and safe error handling code:

  • Catch specific exceptions, such as ValueError or KeyError, instead of using a generic except: clause;
  • Avoid bare except: blocks, as they can mask unexpected problems and make debugging more difficult;
  • Use logging to record exceptions, which helps with monitoring and troubleshooting, rather than simply printing errors or ignoring them;
  • Do not suppress errors silently—always handle exceptions in a way that makes failures visible and traceable.
12345678910111213
import logging logging.basicConfig(level=logging.ERROR, filename='app.log') def divide(a, b): try: return a / b except ZeroDivisionError as e: logging.error("Division by zero attempted: %s", e) # Do not print or ignore the exception return None result = divide(5, 0)
copy

When to Re-raise Exceptions and Document Error Handling

You should re-raise an exception when you need to take some action—such as logging, cleaning up resources, or adding context—but still want the exception to propagate. This ensures that critical errors are not hidden and can be handled at a higher level in your application. Use the raise statement without arguments to re-raise the current exception after your handling logic.

Example Situations to re-raise Exceptions:

  • Logging the error before letting it propagate;
  • Cleaning up files or connections before re-raising;
  • Adding additional context to the error message, then re-raising.

Documenting Error Handling in your Code:

  • Use comments to explain why exceptions are caught or re-raised in complex blocks;
  • Add docstrings to functions and methods that describe which exceptions might be raised or handled;
  • Clearly state any side effects or cleanup actions performed during exception handling.

Sample Docstring:

def read_file(path):
    """
    Reads the contents of a file at the given path.
    Raises:
        FileNotFoundError: If the file does not exist.
        PermissionError: If the file cannot be accessed due to permissions.
    """
    # Error handling logic here

Clear documentation and thoughtful re-raising of exceptions help others understand your code, prevent silent failures, and make maintenance safer and more predictable.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 2
some-alt