In Python, it is possible to use one-liners to set values with special conditions (such as defaults or conditions) in a simple, intuitive way.
result = 0 or "Does not exist." # "Does not exist."
result = "Found user!" if user in user_list else "User not found."
Is it possible to write a similar statement that catches exceptions?
from json import loads
result = loads('{"value": true}') or "Oh no, explosions occurred!"
# {'value': True}
result = loads(None) or "Oh no, explosions occurred!"
# "Oh no, explosions occurred!" is desired, but a TypeError is raised.
It is not possible to do a one-line exception-handling statement in python. One could write a function to do this.
Example usage:
Multiple arguments are supported
The error-catching process may still be interrupted:
If this behavior is undesired, use
BaseException
:It is possible in one line using exec: