[英]Creating Function to handle exceptions in Python
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. 我想知道是否有可能编写一个函数来避免调用
try ... except
每次都会阻塞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. 在这段代码中,Python运行
divider(1,0)
并尝试将结果作为参数传递给e
函数。
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. 我想要做的是将一个函数作为参数传递,并在
try ... except
块中运行它,以便在发生任何错误时将错误直接添加到日志中。
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
. 您的示例不起作用,因为您将函数调用
divider(1,0)
的“结果”提供给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
. 您需要将函数本身和任何参数传递给
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: Doku:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.