📄 node10.html
字号:
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()</pre></div><P>The use of the <tt class="keyword">else</tt> clause is better than adding additional
code to the <tt class="keyword">try</tt> clause because it avoids accidentally
catching an exception that wasn't raised by the code being protected
by the <tt class="keyword">try</tt> ... <tt class="keyword">except</tt> statement.<P>使用 <tt class="keyword">else</tt> 子句比在 <tt class="keyword">try</tt> 子句中附加代码要好,因为这样可以避免 <tt class="keyword">try</tt> ...<BR>keywordexcept 意外的截获本来不属于它们保护的那些代码抛出的异常。<P>When an exception occurs, it may have an associated value, also known as
the exception's <em>argument</em>.
The presence and type of the argument depend on the exception type.<P>发生异常时,可能会有一个附属值,作为异常的参数存在。这个参数是否存在、是什么类型,依赖于异常的类型。<P>The except clause may specify a variable after the exception name (or list).
The variable is bound to an exception instance with the arguments stored
in <code>instance.args</code>. For convenience, the exception instance
defines <tt class="method">__getitem__</tt> and <tt class="method">__str__</tt> so the arguments can
be accessed or printed directly without having to reference <code>.args</code>.<P>在异常名(列表)之后,也可以为 except 子句指定一个变量。这个变量绑定于一个异常实例,它存储在 <code>instance.args</code> 的参数中。为了方便起见,异常实例定义了 <tt class="method">__getitem__</tt> 和 <tt class="method">__str__</tt>,这样就可以直接访问过打印参数而不必引用 <code>.args</code>。<P><div class="verbatim"><pre>
>>> try:
... raise Exception('spam', 'eggs')
... except Exception, inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'instance'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs</pre></div><P>If an exception has an argument, it is printed as the last part
(`detail') of the message for unhandled exceptions.<P>对于未处理的异常,如果它有一个参数,那做就会作为错误信息的最后一部分(“明细”)打印出来。<P>Exception handlers don't just handle exceptions if they occur
immediately in the try clause, but also if they occur inside functions
that are called (even indirectly) in the try clause.
For example:<P>异常处理句柄不止可以处理直接发生在 try 子句中的异常,即使是其中(甚至是间接)调用的函数,发生了异常,也一样可以处理。例如:<P><div class="verbatim"><pre>
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo</pre></div><P><H1><A NAME="SECTION0010300000000000000000"></A><A NAME="raising"></A><BR>8.3 抛出异常 Raising Exceptions </H1><P>The <tt class="keyword">raise</tt> statement allows the programmer to force a
specified exception to occur.
For example:<P>在发生了特定的异常时,程序员可以用 <tt class="keyword">raise</tt> 语句强制抛出异常。例如:<P><div class="verbatim"><pre>
>>> raise NameError, 'HiThere'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere</pre></div><P>The first argument to <tt class="keyword">raise</tt> names the exception to be
raised. The optional second argument specifies the exception's
argument.<P>第一个参数指定了所抛出异常的名称,第二个指定了异常的参数。<P>If you need to determine whether an exception was raised but don't
intend to handle it, a simpler form of the <tt class="keyword">raise</tt> statement
allows you to re-raise the exception:<P>如果你决定抛出一个异常而不处理它, <tt class="keyword">raise</tt> 语句可以让你很简单的重新抛出该异常。<P><div class="verbatim"><pre>
>>> try:
... raise NameError, 'HiThere'
... except NameError:
... print 'An exception flew by!'
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere</pre></div><P><H1><A NAME="SECTION0010400000000000000000"></A><A NAME="userExceptions"></A><BR>8.4 用户自定义异常 User-defined Exceptions </H1><P>Programs may name their own exceptions by creating a new exception
class. Exceptions should typically be derived from the
<tt class="exception">Exception</tt> class, either directly or indirectly. For
example:<P>在程序中可以通过创建新的异常类型来命名自己的异常。异常类通常应该直接或间接的从 <tt class="exception">Exception</tt> 类派生,例如:<P><div class="verbatim"><pre>
>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.value)
...
>>> try:
... raise MyError(2*2)
... except MyError, e:
... print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'</pre></div><P>Exception classes can be defined which do anything any other class can
do, but are usually kept simple, often only offering a number of
attributes that allow information about the error to be extracted by
handlers for the exception. When creating a module which can raise
several distinct errors, a common practice is to create a base class
for exceptions defined by that module, and subclass that to create
specific exception classes for different error conditions:<P>异常类中可以定义任何其它类中可以定义的东西,但是通常为了保持简单,只在其中加入几个属性信息,以供异常处理句柄提取。如果一个新创建的模块中需要抛出几种不同的错误时,一个通常的作法是为该模块定义一个异常基类,然后针对不同的错误类型派生出对应的异常子类。<P><div class="verbatim"><pre>
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message</pre></div><P>Most exceptions are defined with names that end in ``Error,'' similar
to the naming of the standard exceptions.<P>与标准异常相似,大多数异常的命名都以“Error”结尾。<P>Many standard modules define their own exceptions to report errors
that may occur in functions they define. More information on classes
is presented in chapter <A HREF="node11.html#classes"><tex2html_cross_ref_visible_mark></A>, ``Classes.''<P>很多标准模块中都定义了自己的异常,用以报告在他们所定义的函数中可能发生的错误。关于类的进一步信息请参见第 9 章 <A HREF="node11.html#classes"><tex2html_cross_ref_visible_mark></A>,“类”。<P><H1><A NAME="SECTION0010500000000000000000"></A><A NAME="cleanup"></A><BR>8.5 定义清理行为 Defining Clean-up Actions </H1><P>The <tt class="keyword">try</tt> statement has another optional clause which is
intended to define clean-up actions that must be executed under all
circumstances. For example:<P><tt class="keyword">try</tt> 语句还有另一个可选的子句,目的在于定义在任何情况下都一定要执行的功能。例如:<P><div class="verbatim"><pre>
>>> try:
... raise KeyboardInterrupt
... finally:
... print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
KeyboardInterrupt</pre></div><P>A <em>finally clause</em> is executed whether or not an exception has
occurred in the try clause. When an exception has occurred, it is
re-raised after the finally clause is executed. The finally clause is
also executed ``on the way out'' when the <tt class="keyword">try</tt> statement is
left via a <tt class="keyword">break</tt> or <tt class="keyword">return</tt> statement.<P>不管try子句中有没有发生异常, finally 子句都一定会被执行。如果发生异常,在 finally 子句执行完后它会被重新抛出。 <tt class="keyword">try</tt> 子句经由 <tt class="keyword">break</tt> 或 <tt class="keyword">return</tt> 退出也一样会执行 finally 子句。<P>The code in the finally clause is useful for releasing external
resources (such as files or network connections), regardless of
whether or not the use of the resource was successful.<P>在 finally 子句中的代码用于释放外部资源(例如文件或网络连接),不管这些资源是否已经成功利用。<P>A <tt class="keyword">try</tt> statement must either have one or more except clauses
or one finally clause, but not both.<P>在 <tt class="keyword">try</tt> 语句中可以使用若干个 except 子句或一个 finally 子句,但两者不能共存。<P><DIV CLASS="navigation"><div class='online-navigation'><p></p><hr /><table align="center" width="100%" cellpadding="0" cellspacing="2"><tr><td class='online-navigation'><a rel="prev" title="7. 输入和输出 Input and" href="node9.html"><img src='../icons/previous.png' border='0' height='32' alt='Previous Page' width='32' /></A></td><td class='online-navigation'><a rel="parent" title="Python Tutorial" href="tut.html"><img src='../icons/up.png' border='0' height='32' alt='Up One Level' width='32' /></A></td><td class='online-navigation'><a rel="next" title="9. 类 Classes" href="node11.html"><img src='../icons/next.png' border='0' height='32' alt='Next Page' width='32' /></A></td><td align="center" width="100%" class='online-navigation'>Python Tutorial</td><td class='online-navigation'><a rel="contents" title="Table of Contents" href="node2.html"><img src='../icons/contents.png' border='0' height='32' alt='Contents' width='32' /></A></td><td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td><td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td></tr></table><div class='online-navigation'><b class="navlabel">Previous:</b><a class="sectref" rel="prev" href="node9.html">7. 输入和输出 Input and</A><b class="navlabel">Up:</b><a class="sectref" rel="parent" href="tut.html">Python Tutorial</A><b class="navlabel">Next:</b><a class="sectref" rel="next" href="node11.html">9. 类 Classes</A></div></div><hr /></DIV><!--End of Navigation Panel--><ADDRESS>译者:刘鑫(march.liu AT gmail DOT com) 由:limodou转(limodou AT gmail DOT com)<br>See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.</ADDRESS></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -