Suggest a feature

Welcome to TagMyCode

Please login or create account to add a snippet.
Language: Python
Posted by: Ivan Shpotenko
Added: Aug 23, 2017 10:35 AM
Modified: Aug 23, 2017 10:36 AM
Views: 59
Tags: except python try
here's a version of his routine with a couple of minor enhancements:

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.
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.)
  1. def try_except(success, failure, *exceptions):
  2.     try:
  3.         return success() if callable(success) else success
  4.     except exceptions or Exception:
  5.         return failure() if callable(failure) else failure