Sam*_*nga 18 python exception-handling exception
我连续排了很多行,这可能会引发异常,但无论如何,它仍应继续下一行.如何在不单独尝试捕获可能引发异常的每个语句的情况下执行此操作?
try:
this_may_cause_an_exception()
but_I_still_wanna_run_this()
and_this()
and_also_this()
except Exception, e:
logging.exception('An error maybe occured in one of first occuring functions causing the others not to be executed. Locals: {locals}'.format(locals=locals()))
Run Code Online (Sandbox Code Playgroud)
让我们看一下上面的代码,所有函数都可能抛出异常,但它仍然应该执行下一个函数,无论它是否抛出异常.这样做有什么好办法吗?
我不想这样做:
try:
this_may_cause_an_exception()
except:
pass
try:
but_I_still_wanna_run_this()
except:
pass
try:
and_this()
except:
pass
try:
and_also_this()
except:
pass
Run Code Online (Sandbox Code Playgroud)
我认为代码应该仍然继续在异常之后运行,只有当异常是关键的(计算机将烧毁或整个系统将搞砸,它应该停止整个程序,但对于许多小事情也会抛出异常,例如连接我通常没有任何异常处理问题,但在这种情况下,我使用的是第三方库,它很容易抛出小事的异常.
在查看了m4spy的答案后,我认为不可能有一个装饰器,即使其中一个引发异常,它也会让函数中的每一行都执行.
像这样的东西会很酷:
def silent_log_exceptions(func):
@wraps(func)
def _wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception:
logging.exception('...')
some_special_python_keyword # which causes it to continue executing the next line
return _wrapper
Run Code Online (Sandbox Code Playgroud)
或类似的东西:
def silent_log_exceptions(func):
@wraps(func)
def _wrapper(*args, **kwargs):
for line in func(*args, **kwargs):
try:
exec line
except Exception:
logging.exception('...')
return _wrapper
@silent_log_exceptions
def save_tweets():
a = requests.get('http://twitter.com)
x = parse(a)
bla = x * x
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 18
for func in [this_may_cause_an_exception,
but_I_still_wanna_run_this,
and_this,
and_also_this]:
try:
func()
except:
pass
Run Code Online (Sandbox Code Playgroud)
这里有两件事需要注意:
lambda表达式,可调用类等中.except条款是个坏主意,但你可能已经知道了.另一种更灵活的方法是使用更高阶的函数
def logging_exceptions(f, *args, **kwargs):
try:
f(*args, **kwargs)
except Exception as e:
print("Houston, we have a problem: {0}".format(e))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3441 次 |
| 最近记录: |