Python: try-except as an Expression?

Since agf already provided the approach I’d recommend, here’s a version of his routine with a couple of minor enhancements:

def try_except(success, failure, *exceptions):
    try:
        return success()
    except exceptions or Exception:
        return failure() if callable(failure) else failure

This version:

  1. Lets you specify exactly which exceptions will be caught as additional optional arguments. You should always catch the minimum set of exceptions that will do the job and let exceptions you can’t handle bubble up to the caller.

  2. Supports the use of a plain value as well as a function for the failure value. This saves you having to use a lambda in a lot of cases. (Of course, instead of lambda: '' you can just use str.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)