[英]TypeError: exceptions must derive from BaseException
我正在练习 sanfoundary 的异常处理,但我遇到了一个问题,该问题的问题陈述如下:
try:
if '1' != 1:
raise "someError"
else:
print("someError has not occurred")
except "someError":
print ("someError has occurred")
它在运行时返回一个我无法理解的错误,即
Traceback (most recent call last):
File "M:\Prac\test2.py", line 3, in <module>
raise "someError"
TypeError: exceptions must derive from BaseException
在处理上述异常的过程中,又出现了一个异常:
Traceback (most recent call last):
File "M:\Prac\test2.py", line 6, in <module>
except "someError":
TypeError: catching classes that do not inherit from BaseException is not allowed
为了引发自定义异常,您必须首先实现它,不能仅通过将异常命名为字符串来引发异常。 您可以在本文中了解有关如何实现自定义异常的更多信息。
在这种情况下,您可以简单地调用 AssertionError:
try:
if '1' != 1:
raise (AssertionError)
except AssertionError:
print("AssertionError has occurred")
else:
print("AssertionError has not occurred")
有趣的是,将else
语句放在except
之后意味着该子句中的代码只有在没有发生错误时才会运行。
您还可以在文档中找到内置 python 异常列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.