[英]except block does not catch the exception in python
my code is like below 我的代码如下
class Something(models.Model)
def exception(self)
try:
Something.objects.all()
except Exception():
raise Exception()
called this method from testcases ,its working but i need to raise exception ,it does not catch the exception and here is my test case 从测试用例中调用此方法,它可以工作,但是我需要引发异常,它不能捕获异常,这是我的测试用例
def test_exception(self):
instance = Something()
instance.exception()
its working fine but i need to raise exception from except block 它的工作正常,但我需要引发例外块除外
This line: 这行:
except Exception():
should be: 应该:
except Exception:
def exception(self)
try:
Something.objects.all()
except Exception, err:
#print err.message (if you want)
raise err
This will catch the error and print the exact msg if required. 这将捕获错误并在需要时打印确切的味精。
Why catch the Exception just to re-raise it? 为什么要抓住例外只是为了重新提出它? If you are not doing anything in the except suite except re-raising the exception, then simply do not catch the exception in the first place:
如果除了重新引发异常之外,您除了在套件中没有做任何其他事情,那么根本就不用首先捕获异常:
@staticmethod
def exception():
Something.objects.all()
If you are doing something nontrivial inside the except
suite, then: 如果您要在
except
套件中进行一些琐碎的操作,则:
def exception(self):
try:
Something.objects.all()
except Exception:
# do something (with self?)
raise
Then, to test that the exception
method raises an Exception: 然后,要测试
exception
方法是否引发Exception:
def test_exception(self):
instance = Something()
self.assertRaises(Exception, instance.exception)
This depends on Something.objects.all()
raising Exception
. 这取决于
Something.objects.all()
引发Exception
。
PS. PS。 If
exception
does not depend on self
, then it is best to remove it from the argument list and make exception
a staticmethod. 如果
exception
不依赖于self
,那么最好将其从参数列表中删除并将exception
设为静态方法。
PPS. PPS。
Exception
is a very broad base exception class. Exception
是非常广泛的基本异常类。 A more specific exception would be more helpful for debugging, and allow other code to catch this specific exception instead of forcing it to handle any possible Exception
. 更具体的异常对调试更有用,并且允许其他代码捕获此特定的异常,而不是强制其处理任何可能的
Exception
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.