打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
23.6. The raise statement: Cause an exception

Python 2.7 quick reference


23.6. The raise statement: Cause an exception

Python's exception mechanism is the universal framework for dealing with errors—situations where your program can't really proceed normally. For an overview, see Section 25, “Exceptions: Error signaling and handling”.

There are three forms of the raise statement:

raiseraise E1raise E1, E2

The first form is equivalent to “raise None,None” and the second form is equivalent to “raise E1, None”. Each form raises an exception of a given type and with a given value. The type and value depend on how many expressions you provide:

E1E2Exception typeException value
NoneNone Re-raise the current exception, if any. This might be done, for example, inside an except, else, or finally block; see Section 23.8, “The try statement: Anticipate exceptions”.
classNone E1 E1()
class instance of E1 E1E2
classtupleE1 E1(*E2)
classnone of the aboveE1 E1(E2)
instanceNone type(E1) E1

The current recommended practice is to use a raise statement of this form:

raise E(...)

where E is some class derived from the built-in Exception class: you can use one of the built-in exceptions, or you can create your own exception classes.

For classes derived from Exception, the constructor takes one argument, an error message—that is, a string explaining why the exception was raised. The resulting instance makes that message available as an attribute named .message. Example:

>>> try:...     raise ValueError('The day is too frabjous.')... except ValueError as x:...     pass... >>> type(x)<type 'exceptions.ValueError'>>>> x.message'The day is too frabjous.'

To create your own exceptions, write a class that inherits from Exception and passes its argument to the parent constructor, as in this example.

>>> class VocationError(Exception):...     def __init__(self, mismatch):...         Exception.__init__(self, mismatch)... >>> try:...     print "And now, the Vocational Guidance Counsellor Sketch."...     raise VocationError("Does not have proper hat")...     print "This print statement will not be reached."... except VocationError as problem:...     print "Vocation problem: {0}".format(problem)... And now, the Vocational Guidance Counsellor Sketch.Vocation problem: Does not have proper hat
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
一道Python面试题:你真的理解finally了吗?
什么是保留字?Python保留字有哪些?
python3 异常处理try、raise
作文精美句子
python异常处理
关于“异常”
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服