除了块没有在python中捕获异常

Ven*_*chu 1 python exception try-catch

我的代码如下

class Something(models.Model)

    def exception(self)
    try:
       Something.objects.all()
    except Exception():
       raise Exception()
Run Code Online (Sandbox Code Playgroud)

从testcases调用此方法,它的工作,但我需要引发异常,它不会捕获异常,这是我的测试用例

def test_exception(self):
    instance = Something()
    instance.exception()
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我需要从块除外引发异常

Nic*_*tti 7

这一行:

except Exception():
Run Code Online (Sandbox Code Playgroud)

应该:

except Exception:
Run Code Online (Sandbox Code Playgroud)

  • 是的,但当然不应该,因为抓住`Exception`是一个非常糟糕的主意 - 你应该抓住你处理的实际例外,并让其他人冒泡. (2认同)