python - 引发异常“这是错误”和引发“这是错误”之间的区别?
问题描述
我见过人们做这两种方式,但我无法发现它们之间的区别:
raise Exception('This is the error')
和
raise 'This is the error'
我应该使用哪一个?
解决方案
也不要使用。第一个是语法错误:
>>> 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()
推荐阅读
- java - 调用布尔表达式方法的问题
- c# - SQL查询执行顺序
- reactjs - 为什么 webpack 不捆绑 react 组件的 .css 文件?
- firebase - 如何在'Firestore DocumentSnapshot'的for循环中只调用一次函数?
- azure - 数据工厂诊断设置
- maven - Zeppelin hbase 解释器安装无法解决依赖关系
- c# - 'Gdip' 的类型初始化程序在具有 C#.net 核心的 kubernetes pod 中引发异常
- flutter - 从颤振上传图像到firebase存储
- python - 如何在 Django ORM 中使用 PostGIS 聚合函数 ST_AsMVT
- c# - C# WndProc 方法未收到预期的 Msg 类型