【问题标题】:TypeError: exceptions must derive from BaseExceptionTypeError:异常必须从 BaseException 派生
【发布时间】: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

【问题讨论】:

标签: python exception


【解决方案1】:

要引发自定义异常,您必须先实现它,不能仅通过将异常命名为字符串来引发异常。您可以在此article 中了解有关如何实现自定义异常的更多信息。

在这种情况下,您可以简单地调用 AssertionError:

try:
    if '1' != 1:
        raise (AssertionError)
except AssertionError:
    print("AssertionError has occurred")
else:
    print("AssertionError has not occurred")

有趣的是,将else 语句放在except 之后意味着该子句中的代码只有在没有发生错误时才会运行。

你调用还可以在documentation找到一个内置的python异常列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 2021-10-31
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多