【发布时间】:2021-03-22 18:17:46
【问题描述】:
我正在练习 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
【问题讨论】:
-
raise "someError"是错误的,因为你想提出一个Exception对象,但实际上你提出了一个str对象。这回答了你的问题了吗? Proper way to declare custom exceptions in modern Python?