I was wondering if it's possible to write a function to avoid calling a try ... except
block each time for risky functions in Python.
I tried following code but it didn't work:
def e(methodtoRun):
try:
methodtoRun.call()
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
def divider(a, b):
return a / b
e(divider(1,0))
In this code, Python runs divider(1,0)
and tries to pass result as an argument to the e
function.
What I wanted to do is to pass a function as an argument and run it in the function try ... except
block so that, if any error occurs, I will add the error to a log directly.
Is this possible?
You can do this .. but it does make code not really better to read.
Your example does not work, because you feed the "result" of the function-call divider(1,0)
to e
. It never comes to handling the exception because you already called the function and the exception already happened.
You need to pass the function itself and any params to e
.
Change it to:
def e(methodtoRun, *args):
try:
methodtoRun(*args) # pass arguments along
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
def divider(a, b):
return a / b
e(divider,1,0) # give it the function and any params it needs
To get:
<type 'exceptions.ZeroDivisionError'>
('integer division or modulo by zero',)
integer division or modulo by zero
In any serious code review you should get your code back to fix this though. I strongly recommend to not do this - you are only capturing the most general exception and making this construct more flexible will make it horrible to use!
Exceptions should be:
your code is doing the exact opposit.
Doku:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.