同一异常的多个异常处理程序 [英] Multiple exception handlers for the same Exception

查看:185
本文介绍了同一异常的多个异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以在被调用的函数中,我有一个巨大的尝试块-catch语句为。

  def Called():
try:
#All语句为函数在try块。
除了A:
#异常处理程序。
除了B:
#异常处理程序。
除了A:
#异常处理程序。

我遇到的问题是我需要抓住两个相同类型的异常(在不同的位置被叫功能)。然后由Calling功能处理。



一种方法是在Called函数内定义两个try-except块。但是我不了解Calling函数如何处理两种不同类型的异常。

解决方案

广告;只有第一个除了A 子句将永远被执行。您需要的是内的中的逻辑,以进一步检查异常,或者(如果 try 块中的代码允许)几个尝试 - 块。



前一种方法的示例:

  try:
something_that_might_fail()
除了A为e:
如果e.is_harmless ():
pass
elif e.is_something_we_can_handle():
handle_it()
else:
raise#re-raise希望它进一步处理堆栈


I have a code for a function which is called inside another function.(Result of refactoring).

So in the called function I have a huge block of try-catch statements as.

def Called():
     try:
         #All statements for the function in the try block.
     except A:
         # Exception handler.
     except B:
         # Exception handler.
     except A: 
         # Exception handler.

The problem I have is that I need to catch two exceptions of the same type (At different locations in the Called function). Which then are handled by the Calling function.

One way would be to define two try-except blocks within the Called function. But I am not understanding how the Calling function can handle two exceptions of the same type differently.

解决方案

This won't work as advertised; only the first except A clause will ever get executed. What you need is either some logic inside the clause to further inspect the exception, or (if the code inside the try block permits) several try-except blocks.

Example of the former approach:

try:
    something_that_might_fail()
except A as e:
    if e.is_harmless():
        pass
    elif e.is_something_we_can_handle():
        handle_it()
    else:
        raise    # re-raise in the hope it gets handled further up the stack

这篇关于同一异常的多个异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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