Skip to content
Advertisement

Python exception: execute code if a specific exception is raised or else

Let’s say I have the following code, that assign 1 and print it in case the value is None or not negative.

value = None

class NegativeNumber(Exception):
    pass
class NotFound(Exception):
    pass

try:
    if value is None:
        raise NotFound
    elif value < 0:
        raise NegativeNumber
except NegativeNumber:
    print("Error: negative number")
except NotFound:
    value = 1
    print(value)
else:
    value = 1
    print(value)

Is there a way to avoid repeat twice to assign value=1 and print it?

It would be ideal something like except NotFound or else, but I have not found anything similar in python.

Advertisement

Answer

There is no except ... or else: construct. Suppress the exception inside the try block to trigger the else block for the exception as well:

try:
    try:
        if value is None:
            raise NotFound
        elif value < 0:
            raise NegativeNumber
    except NotFound:
        pass  # suppress exception
except NegativeNumber:
    print("Error: negative number")
else:
    value = 1
    print(value)

Instead of using try/except to suppress the exception, contextlib.suppress can be used instead. This can make the intention clearer, as it explicitly names how the exception is handled.

try:
    with suppress(NotFound):
        if value is None:
            raise NotFound
        elif value < 0:
            raise NegativeNumber
except NegativeNumber:
    print("Error: negative number")
else:
    value = 1
    print(value)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement