引发异常“This is the error”和引发异常“This is the error”之间的区别?

2024-04-25 13:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我见过有人这样做,但我看不出他们之间的区别:

raise Exception('This is the error')

以及

raise 'This is the error'

我应该用哪一个?你知道吗


Tags: theisexceptionerrorthisraise区别
1条回答
网友
1楼 · 发布于 2024-04-25 13:21:35

两个都不要用。第一个是语法错误:

>>> raise Exception "This is an error"
  File "<stdin>", line 1
    raise Exception "This is an error"
                                     ^
SyntaxError: invalid syntax

第二个是类型错误(不能“提升”一个str值):

>>> raise "this"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException

正确的形式是使用错误消息作为参数调用异常类型:

raise Exception("this is the error")

在所需异常不需要参数的情况下,引发Exception类型本身相当于引发不带参数创建的实例。你知道吗

raise Exception   # equivalent to raise Exception()

相关问题 更多 >

    热门问题