Reputation: 631
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')
Upvotes: 6
Views: 28595
Reputation: 9125
While there is no such function for the general case, there is one that solves your particular problem:
x = '123'
x.isnumeric()
returns True
while
x = 'as1f'
x.isnumeric()
returns False
Upvotes: 0
Reputation: 1122552
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)
Upvotes: 5