Skip to main content

ExceptionHandler: Decorator for Exception Handling

ExceptionHandler is an open-source Python library for simplyfying exception handling. It makes Python handling exception code cleaner and more readable.

Installation

To install ExceptionHandler, use pip with the following command:

pip install exception-handling-decorator

Releases

Latest releases of ExceptionHandler can be found at the PyPI repository: ExceptionHandler on PyPI

Source Code

The source code is stored at the GitHub repository: ExceptionHandler on GitHub

Getting started

Import ExceptionHandler:

from exception_handler import ExceptionHandler

Use @ExceptionHandler decorator with the following parameters:

exception=Exception - Exception(s) to be cР°ught. It can be of type Exception or its descendant or tuple[Exception].

handling_func=None - Function(s) to handle exception(s). It can be of type Callable or its descendant or tuple[Callable]. If handling_func is None, the exception will not be handled. If there more than one handling function (tuple[Callable]), every function will handle the corresponding Exception.

reraise=True - Indicates if the excaption(s) should be reraised. It can be of type bool or its descendant or tuple[bool]. If there more than one reraise (tuple[bool]), every tuple member will raise the corresponding Exception.

Example 1

The following code handles a ZeroDivisionError with classic try/except catching, prints and re-raise the exception:

def print_exception(ex):
    print(ex)

def divide_by_zero():
    try:
        return 1 / 0
    except ZeroDivisionError as e:
        print_exception(e)   
        raise

divide_by_zero()

We can simplify divide_by_zero() function by using @ExceptionHandler decorator:

@ExceptionHandler(exception=ZeroDivisionError, handling_func=print_exception, reraise=True)
def divide_by_zero():
    return 1 / 0   

The final code:

from exception_handler import ExceptionHandler
def print_exception(ex):
    print(ex)

@ExceptionHandler(exception=ZeroDivisionError, handling_func=print_exception, reraise=True)
def divide_by_zero():
    return 1 / 0  

divide_by_zero()  

Example 2

The following code raises randomly one of two custom exceptions:

import random
import logging

class SomeException(Exception):

    def __str__(self) -> str:
        return "SomeException message"

class SomeOtherException(Exception):
    def __str__(self) -> str:
        return "SomeOtherException message"

def get_rand_bool():
    """
    Returns random boolean value
    """
    rand_int = random.getrandbits(1)
    return bool(rand_int)

def log_exception(ex):
    logging.error(ex)


def print_exception(ex):
    print(ex)    


def do_something():
    if get_rand_bool():
        try:
            raise SomeException
        except SomeException as e:
            print_exception(e)
            raise
            
    try:
        raise SomeOtherException
    except SomeOtherException as e:
        log_exception(e)

do_something()

We can simplify do_something() function by using @ExceptionHandler decorator:

@ExceptionHandler(exception=(SomeException, SomeOtherException), 
                  handling_func=(print_exception, log_exception), 
                  reraise=(True,False))
def do_something():
    if get_rand_bool():
        raise SomeException
    raise SomeOtherException

The final code:

import random
from exception_handler import ExceptionHandler
import logging

class SomeException(Exception):

    def __str__(self) -> str:
        return "SomeException message"

class SomeOtherException(Exception):
    def __str__(self) -> str:
        return "SomeOtherException message"

def get_rand_bool():
    """
    Returns random boolean value
    """
    rand_int = random.getrandbits(1)
    return bool(rand_int)

def log_exception(ex):
    logging.error(ex)


def print_exception(ex):
    print(ex)  

@ExceptionHandler(exception=(SomeException, SomeOtherException), 
                  handling_func=(print_exception, log_exception), 
                  reraise=(True,False))
def do_something():
    if get_rand_bool():
        raise SomeException
    raise SomeOtherException  

do_something()

Metadata

Release files for exception-handling-decorator 0.1.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for exception-handling-decorator 0.1.8
File Size Uploaded
exception-handling-decorator-0.1.8.tar.gz 3.4 kB Details

Release files / exception-handling-decorator-0.1.8.tar.gz

Download URL exception-handling-decorator-0.1.8.tar.gz
Size 3.4 kB
Tags Source
SHA-256 checksum
How to use checksums
5c907e5ac2866034f181f11e727c74a4b119cb73de1912e3efc93117ce527da8
BLAKE2b-256 checksum
How to use checksums
198b24931ab3c2f6a0a666f96353a8cc2079ed0db541380b1cb37ca41568b7c1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.8.0

Release history Release notifications | RSS feed

This release

0.1.8 This release

1 release file

0.1.7

1 release file

0.1.6

1 release file

0.1.5

1 release file

0.1.4

1 release file

0.1.3

1 release file

0.1.2

1 release file

0.1.1

1 release file

0.1.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page