0

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.

2
  • 1
    I don't see the point of raising NotFound here. Just don't raise it and things work as desired. Commented Jun 2, 2021 at 15:13
  • it's just an example to illustrate my point. The real scenario is the case in which an external function/class raises an error (so no control about it), but one wants to ignore one specific exception but not all the others Commented Jun 2, 2021 at 15:16

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, the solution with suppress is awesome

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.