如何在Python中引发异常,以便稍后可以通过except块捕获它?
当前回答
首先阅读现有答案,这只是一个附录。
请注意,可以使用或不使用参数引发异常。
例子:
raise SystemExit
退出程序,但您可能想知道发生了什么。所以你可以用这个。
raise SystemExit("program exited")
这将在关闭程序之前将“程序退出”打印为标准错误。
其他回答
引发异常的另一种方法是使用断言。您可以使用断言来验证条件是否得到满足。如果没有,那么它将引发AssertionError。有关详细信息,请查看此处。
def avg(marks):
assert len(marks) != 0, "List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:", avg(mark2))
mark1 = []
print("Average of mark1:", avg(mark1))
您可能还想引发自定义异常。例如,如果您正在编写一个库,那么为您的模块创建一个基本异常类,然后创建自定义子异常是一个非常好的做法。
您可以这样实现:
class MyModuleBaseClass(Exception):
pass
class MoreSpecificException(MyModuleBaseClass):
pass
# To raise custom exceptions, you can just
# use the raise keyword
raise MoreSpecificException
raise MoreSpecificException('message')
如果您对拥有自定义基类不感兴趣,您可以从普通异常类(如exception、TypeError、ValueError等)继承自定义异常类。
为此,您应该学习Python的raise语句。
它应该保存在试块内。
示例-
try:
raise TypeError # Replace TypeError by any other error if you want
except TypeError:
print('TypeError raised')
如何在Python中手动抛出/引发异常?
使用语义上符合您问题的最具体的异常构造函数。
在您的信息中要明确,例如:
raise ValueError('A very specific bad thing happened.')
不引发一般异常
避免引发一般异常。要捕获它,您必须捕获它的子类的所有其他更具体的异常。
问题1:隐藏错误
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
例如:
def demo_bad_catch():
try:
raise ValueError('Represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)
问题2:抓不住
更具体的捕获不会捕获一般的异常:
def demo_no_catch():
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
>>> demo_no_catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
最佳实践:提高陈述
相反,请使用语义上符合您的问题的最具体的异常构造函数。
raise ValueError('A very specific bad thing happened')
这也方便地允许将任意数量的参数传递给构造函数:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
这些参数由Exception对象的args属性访问。例如:
try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
印刷品
('message', 'foo', 'bar', 'baz')
在Python 2.5中,BaseException中添加了一个实际的消息属性,以鼓励用户将异常子类化并停止使用args,但消息的引入和最初对args的弃用已经被撤回。
最佳实践:条款除外
例如,当在except子句中时,您可能希望记录发生了特定类型的错误,然后重新引发。在保留堆栈跟踪的同时执行此操作的最佳方法是使用裸raise语句。例如:
logger = logging.getLogger(__name__)
try:
do_something_in_app_that_breaks_easily()
except AppError as error:
logger.error(error)
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
不要修改错误。。。但如果你坚持的话。
您可以使用sys.exc_info()保留堆栈跟踪(和错误值),但这更容易出错,并且在Python 2和3之间存在兼容性问题,因此更倾向于使用裸提升来重新提升。
为了解释,sys.exc_info()返回类型、值和回溯。
type, value, traceback = sys.exc_info()
这是Python 2中的语法-请注意,这与Python 3不兼容:
raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
如果需要,您可以修改新的提升发生的情况,例如为实例设置新的参数:
def error():
raise ValueError('oops!')
def catch_error_modify_message():
try:
error()
except ValueError:
error_type, error_instance, traceback = sys.exc_info()
error_instance.args = (error_instance.args[0] + ' <modification>',)
raise error_type, error_instance, traceback
我们在修改参数时保留了整个回溯。请注意,这不是最佳实践,在Python3中它是无效的语法(使保持兼容性变得更加困难)。
>>> catch_error_modify_message()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch_error_modify_message
File "<stdin>", line 2, in error
ValueError: oops! <modification>
在Python 3中:
raise error.with_traceback(sys.exc_info()[2])
再次:避免手动操作回溯。它的效率更低,更容易出错。如果您使用的是线程和sys.exc_info,甚至可能会得到错误的回溯(特别是如果您对控制流使用异常处理,我个人倾向于避免这种情况)
Python 3,异常链接
在Python 3中,您可以链接Exceptions,以保留回溯:
raise RuntimeError('specific message') from error
请注意:
这确实允许更改引发的错误类型,并且这与Python 2不兼容。
不推荐的方法:
这些可以很容易地隐藏,甚至进入生产代码。你想引发一个异常,这样做会引发一个例外,但不是预期的!
以下内容在Python 2中有效,但在Python 3中无效:
raise ValueError, 'message' # Don't do this, it's deprecated!
仅在较旧版本的Python(2.4及更低版本)中有效,您可能仍然会看到有人提出字符串:
raise 'message' # really really wrong. don't do this.
在所有现代版本中,这实际上都会引发TypeError,因为您没有引发BaseException类型。如果您没有检查正确的异常,并且没有一个知道该问题的审查人员,那么它可能会进入生产。
示例用法
我提出异常以警告用户如果他们不正确使用我的API:
def api_func(foo):
'''foo should be either 'baz' or 'bar'. returns something very useful.'''
if foo not in _ALLOWED_ARGS:
raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
创建自己的错误类型
“我想故意犯一个错误,这样它就会进入例外”
您可以创建自己的错误类型,如果您想指出应用程序的某些特定错误,只需在异常层次结构中的适当点子类即可:
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
和用法:
if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.')
在Python 3中,有四种不同的语法用于引发异常:
引发异常引发异常(args)提升从original_exception引发异常(args)
1.引发异常vs.2。引发异常(args)
如果使用引发异常(args)引发异常,则在打印异常对象时将打印这些参数,如下例所示。
# Raise exception (args)
try:
raise ValueError("I have raised an Exception")
except ValueError as exp:
print ("Error", exp) # Output -> Error I have raised an Exception
# Raise exception
try:
raise ValueError
except ValueError as exp:
print ("Error", exp) # Output -> Error
3.声明提出
没有任何参数的raise语句重新引发最后一个异常。
如果您在捕获异常后需要执行一些操作,然后想要重新引发异常,那么这很有用。但是如果之前没有任何异常,那么raise语句会引发TypeError异常。
def somefunction():
print("some cleaning")
a=10
b=0
result=None
try:
result=a/b
print(result)
except Exception: # Output ->
somefunction() # Some cleaning
raise # Traceback (most recent call last):
# File "python", line 8, in <module>
# ZeroDivisionError: division by zero
4.从original_exception引发异常(args)
此语句用于创建异常链接,其中响应另一个异常而引发的异常可以包含原始异常的详细信息,如下例所示。
class MyCustomException(Exception):
pass
a=10
b=0
reuslt=None
try:
try:
result=a/b
except ZeroDivisionError as exp:
print("ZeroDivisionError -- ",exp)
raise MyCustomException("Zero Division ") from exp
except MyCustomException as exp:
print("MyException",exp)
print(exp.__cause__)
输出:
ZeroDivisionError -- division by zero
MyException Zero Division
division by zero
推荐文章
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?
- Tensorflow 2.0:模块“Tensorflow”没有属性“Session”
- 从环境文件中读入环境变量
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)
- 如何删除熊猫数据帧的最后一行数据