处理除一个例外之外的所有内容 [英] Handling all but one exception

查看:102
本文介绍了处理除一个例外之外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try:
something
除了NoChildException:
raise NoChildException
除了:
pass


解决方案

答案是简单地做 raise

 尝试:
...
除了SomeException:
raise
除了:
...

raise 没有任何表达式,它会简单地提高最后抛出的异常(即使它已被处理!)。大致相当于:

  except SomeException as e:
raise e

如果您认为另一个异常可能会在catch块中抛出(在这种情况下显然是不可能的),则应使用后一种格式,提出正确的例外。



但是,如我的评论中所述:


简单的答案:不要。捕获所有
异常是非常糟糕的做法,因为你会倾向于捕捉你不想要的东西,
模糊错误。
只有少量的合法案例做这样的事情。


只要抓住你认为你的错误代码可能会抛出,你知道如何处理,并离开任何其他人。如果还有其他事情发生,您的程序将会退出 - 这是您想要的,因为您可以看到它为什么发生并正确处理。


How to handle all but one exception ?

try:
    something
except NoChildException:
    raise NoChildException
except:
    pass

解决方案

The answer is to simply do raise:

try:
    ...
except SomeException:
    raise
except:
    ...

raise without any expression after it will simple raise the last thrown exception (even if it's been handled!). It's roughly equivalent to:

except SomeException as e:
    raise e

If you think another exception might be thrown in the catch block (obviously impossible in this case), you should use the latter format to ensure you re-raise the right exception.

However, as noted in my comment:

Simple answer: Don't. It's really bad practice to catch all exceptions, as you will tend to catch ones you didn't mean to, obscuring errors. There are only a tiny number of legitimate cases for doing such a thing.

Just catch the errors that you think your code might throw, and you know how to handle, and leave any others. If anything else happens, your program will then exit out - which is what you want, as you can then see why it occurred and handle it correctly.

这篇关于处理除一个例外之外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆