27 Oct 2019

Exceptions in Python

Use Specific Exceptions

Allows you to differentiate between various errors and deliver accurate error messages, making issue identification and resolution more efficient

try:
    # some code
except FileNotFoundError:
    # handle file not found
except IndexError
    # handle index error

Implement Error Logging

Utilizing the logging module you can capture exceptions along with vital information like timestamps, error details, stack traces

import logging

logging.basicConfig(filename'error.log', level=logging.ERROR)

try:
    # some code
except Exception as e:
    logging.error('An error occurred: %s', str(e))

Custom Exception Classes

Better code readability, improved error handling and modular project development.

Use finally for Cleanup Tasks

Ensures that the code will execute regardless of whether an exception occurred or not.

try:
    # code that may raise an exception
except Exception as e:
    # handle it
else: 
    # code that executes if no exceptions are raised
finally: 
    # code that will always execute