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.

JavaScript

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:

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement