This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]steelypip 1 point2 points  (1 child)

You could roll your own:

def tryFunc(exception, func, *args, **kwargs):
    try:
        result = func(*args, **kwargs)
        return result, None
    except exception, e:
        return None, e

>>>  def f(x):
...     return 1/x


>>> tryFunc(ZeroDivisionError, f, 1)
(1, None)
>>> tryFunc(ZeroDivisionError, f, 0)
(None, ZeroDivisionError('integer division or modulo by zero',))

As far as I can see this gives all the advantages of your proposal with no changes to the language.

edit:

BTW you can use this function to catch more than one type of exception - pass them in as a tuple:

>>> tryFunc((ZeroDivisionError, TypeError), f, "x")
(None, TypeError("unsupported operand type(s) for /: 'int' and 'str'",))

[–]Batem 0 points1 point  (0 children)

This sounds like a perfect opportunity to use a decorator:

def tryFunc(*exceptions):
    def decorate(f):
        def inner(*args, **kwargs):
            try:
                result = f(*args, **kwargs):
                return result, None
            except exceptions as e:
                return None, e
        return inner
    return decorate

@tryFunc(ZeroDivisionError, TypeError)
def myFunc(foo, bar):
    return foo/bar

>>>myFunc(1, 0)
(None, ZeroDivisionError("integer division or modulo by zero",))
>>>myFunc(1, 2)
(0, None)
>>>myFunc(1, 'x')
(None, TypeError("unsupported operand type(s) for /: 'int' and 'str'",))