Repacking or wrapping of imported error or exception types in python3 modules

Viewed 123

I have this module A that might raise an exception from an imported module B. Can I "wrap" or "repack" the exception so that I can handle the exception in the importing script without having to import B?

A.py:

import B

def do_something(parameters):
    try:
        B.function(**parameters)
    except B.some_exception as eee:
        raise wrapper(eee)

script.py

import A

try:
    do_something("glorious parameter")
except B.wrapped_exception:
    handling()
1 Answers

You could just import the exception from B like

from B import some_exception

or add a general exception catch with some other logic, like a matching message, to check if it the specific exception like

try:
    do_something("glorious parameter")
except Exception as e:
    if str(e) == "Matching message":
        handling()
    else:
        raise e

However, bare exceptions are usually not recommended because they indiscriminately catch everything (What is wrong with using a bare 'except'?) so I would go with your original solution or the first suggestion.

Edit:

I re-read your issue and I think I got what you meant. You can chain exceptions with the keyword from and raise some general error like ValueError such as:

def do_something(parameters):
    try:
        B.function(**parameters)
    except B.some_exception as eee:
        raise ValueError("Wrapped exception") from eee

and then catch the ValueError as usual.

See: Python "raise from" usage

Related