True if a function works and false if a function gives an error

14,694

There is no such function. You couldn't build a function that does what you ask for, because by the time Python calls iserror(), the float('123') or float('as1f') expression has already been executed; if an exception is raised there, iserror() is never executed.

You'd have to delegate calling to the function:

def iserror(func, *args, **kw):
    try:
        func(*args, **kw)
        return False
    except Exception:
        return True

then use it like this:

iserror(float, '123')   # False
iserror(float, 'as1f')  # True

Catching all errors is not that great an idea however. Although the above function tries to do the right thing by catching Exception (and thus avoids catching SystemExit or KeyboardInterrupt), it will catch MemoryError, which indicates you ran out of memory, not that the arguments to the function you tested were wrong!

Always try to catch specific exceptions; you could extend iserror() to take a specific exception:

def iserror(func, *args, **kw):
    exception = kw.pop('exception', Exception)
    try:
        func(*args, **kw)
        return False
    except exception:
        return True

then only catch ValueError to test your float() calls:

iserror(float, '123', exception=ValueError)   # False
iserror(float, 'as1f', exception=ValueError)  # True

This is no longer all that readable. I'd just stick with a simple inline try..except wherever you want to use a function call that could raise an exception, because then you can tailor your response to the specific exception without having to repeat yourself to handle the result after you determined there won't be an error:

while True:
    value = raw_input('Please give a number: ')
    try:
         value = int(value)
         break
    except ValueError:
         print "Sorry, {} is not a valid number, try again".format(value)
Share:
14,694
Ignasi
Author by

Ignasi

Updated on June 05, 2022

Comments

  • Ignasi
    Ignasi almost 2 years

    Is there any way in python (built-in function or something) to check if a function execution fails due to an error or works? And return either true or false depending on the case it is

    Example of what I would expect to happen:

    Builtin method example: iserror

    iserror(float('123')) #returns False, as no error on float('123') occurs
    iserror(float('as1f')) #returns True, as it is not possible to convert to float the string ('as1f')
    
  • Dave C
    Dave C over 2 years
    It's neat to learn about this function, but it's practically unusable. '59'.isnumeric() yields True, but '-59'.isnumeric() yields False. I still consider the string '-59' to be 'numeric'.