except块未捕获python中的异常

1 投票
3 回答
6220 浏览
提问于 2025-04-17 04:41

我的代码如下:

class Something(models.Model)

    def exception(self)
    try:
       Something.objects.all()
    except Exception():
       raise Exception()

我在测试案例中调用了这个方法,它运行得很好,但我需要抛出一个异常,它并没有捕捉到这个异常。以下是我的测试案例:

def test_exception(self):
    instance = Something()
    instance.exception()

它运行得不错,但我需要在异常处理的地方抛出一个异常。

3 个回答

0

为什么要捕获异常然后再抛出它呢?如果你在捕获异常的代码块里什么都不做,只是重新抛出异常,那你根本就不需要捕获这个异常。

@staticmethod
def exception():
    Something.objects.all()

如果你在except代码块里做了一些比较复杂的事情,那就另当别论了:

def exception(self):
    try:
        Something.objects.all()
    except Exception:
        # do something (with self?)
        raise 

接下来,要测试exception方法是否会抛出异常:

def test_exception(self):
    instance = Something()
    self.assertRaises(Exception, instance.exception)

这取决于Something.objects.all()是否会抛出Exception


另外,如果exception不依赖于self,那么最好把它从参数列表中移除,并把exception改成一个静态方法。

还有,Exception是一个非常广泛的异常类。使用更具体的异常类会更有助于调试,也能让其他代码捕获这个特定的异常,而不是被迫处理所有可能的Exception

8

这一行:

except Exception():

应该改成:

except Exception:
2
def exception(self)
    try:
        Something.objects.all()
    except Exception, err:
        #print err.message (if you want)
        raise err

这样做可以捕捉到错误,并在需要的时候打印出具体的错误信息。

撰写回答