python except exception_处理在except子句中发生的Python异常

在Python 2.x中,当异常处理代码可能引发新的异常时,如何确保只抛出原始异常并忽略后续异常?这篇博客讨论了这个问题,并提供了解决方案,包括使用函数抽象和保存原始异常再重新抛出的方法。强调了精确捕获预期异常的重要性,以防止意外错误的发生。
摘要由CSDN通过智能技术生成

I have some code in a Python except clause that is intended to do some logging, but the logging code might itself cause an exception. In my case, I'd like to just ignore any second exception that might occur, and raise the original exception. Here is a very simplified example:

try:

a = this_variable_doesnt_exist

except:

try:

1/0

except:

pass

raise

Running the above code, I hope to get:

NameError: name 'this_variable_doesnt_exist' is not defined

but instead, in Python 2.x, I get:

ZeroDivisionError: integer division or modulo by zero

I've discovered that in Python 3.x, it does what I want.

I couldn't find much commentary on this in the Python 2.x docs (unless I missed it). Can I achieve this in 2.x?

解决方案

With abstraction:

def log_it():

try:

1 / 0

except:

pass

try:

this = that

except:

log_it()

raise

Does what you want in Python 2.5

Another way to do it is to store the exception in a variable, then re-raise it explicitly:

try:

this = that

except NameError, e: # or NameError as e for Python 2.6

try:

1 / 0

except:

pass

raise e

Note that you probably shouldn't just be using a bare except to catch everything that might come - it's usually best to catch the specific exceptions you expect to occur in case a drastic and fatal exception (like being out of memory) occurs.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值