首页 > 解决方案 > 引发异常“这是错误”和引发“这是错误”之间的区别?

问题描述

我见过人们做这两种方式,但我无法发现它们之间的区别:

raise Exception('This is the error')

raise 'This is the error'

我应该使用哪一个?

标签: pythonpython-3.xexceptiontry-catch

解决方案


也不要使用。第一个是语法错误:

>>> 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()

推荐阅读