⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 node10.html

📁 python的入门教程,讲得挺不错的,有一些实例
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//CN"><html><head><link rel="STYLESHEET" href="style.css" type='text/css' /><link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" /><link rel='start' href='../index.html' title='Python Documentation Index' /><link rel="first" href="tut.html" title='Python Tutorial' /><link rel='contents' href='node2.html' title="Contents" /><link rel='last' href='about.html' title='About this document...' /><link rel='help' href='about.html' title='About this document...' /><link rel="next" href="node11.html" /><link rel="prev" href="node9.html" /><link rel="parent" href="tut.html" /><link rel="next" href="node11.html" /><meta name='aesop' content='information' /><title>8. 错误和异常 Errors and Exceptions </title></head><body><DIV CLASS="navigation"><div id='top-navigation-panel' xml:id='top-navigation-panel'><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><hr /></div></DIV><!--End of Navigation Panel--><div class='online-navigation'><!--Table of Child-Links--><A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a><UL CLASS="ChildLinks"><LI><A href="node10.html#SECTION0010100000000000000000">8.1 异常 Exceptions</a><LI><A href="node10.html#SECTION0010200000000000000000">8.2 处理异常 Handling Exceptions</a><LI><A href="node10.html#SECTION0010300000000000000000">8.3 抛出异常 Raising Exceptions</a><LI><A href="node10.html#SECTION0010400000000000000000">8.4 用户自定义异常 User-defined Exceptions</a><LI><A href="node10.html#SECTION0010500000000000000000">8.5 定义清理行为 Defining Clean-up Actions</a></ul><!--End of Table of Child-Links--></div><HR><H1><A NAME="SECTION0010000000000000000000"></A><A NAME="errors"></A><BR>8. 错误和异常 Errors and Exceptions </H1><P>Until now error messages haven't been more than mentioned, but if you
have tried out the examples you have probably seen some.  There are
(at least) two distinguishable kinds of errors:
<em>syntax errors</em> and <em>exceptions</em>.<P>至今为止还没有进一步的谈论过错误信息,不过在你已经试验过的那些例子中,可能已经遇到过一些。Python 中(至少)有两种错误:语法错误和异常( <em>syntax errors</em>and <em>exceptions</em> )。<P>section语法错误 Syntax Errors <A NAME="syntaxErrors"></A><P>Syntax errors, also known as parsing errors, are perhaps the most common
kind of complaint you get while you are still learning Python:<P>语法错误,也称作解析错误,可能是学习 Python 的过程中最容易犯的:<P><div class="verbatim"><pre>
&gt;&gt;&gt; while True print 'Hello world'
  File "&lt;stdin&gt;", line 1, in ?
    while True print 'Hello world'
                   ^
SyntaxError: invalid syntax</pre></div><P>The parser repeats the offending line and displays a little `arrow'
pointing at the earliest point in the line where the error was
detected.  The error is caused by (or at least detected at) the token
<em>preceding</em> the arrow: in the example, the error is detected at
the keyword <tt class="keyword">print</tt>, since a colon ("<tt class="character">:</tt>") is missing
before it.  File name and line number are printed so you know where to
look in case the input came from a script.<P>解析器会重复出错的行,并在行中最早发现的错误位置上显示一个小箭头。错误(至少是被检测到的)就发生在箭头指向的位置。示例中的错误表现在关键字<tt class="keyword">print</tt> 上,因为在它之前少了一个冒号( "<tt class="character">:</tt>")。同时也会显示文件名和行号,这样你就可以知道错误来自哪个脚本,什么位置。<P><H1><A NAME="SECTION0010100000000000000000"></A><A NAME="exceptions"></A><BR>8.1 异常 Exceptions </H1><P>Even if a statement or expression is syntactically correct, it may
cause an error when an attempt is made to execute it.
Errors detected during execution are called <em>exceptions</em> and are
not unconditionally fatal: you will soon learn how to handle them in
Python programs.  Most exceptions are not handled by programs,
however, and result in error messages as shown here:<P>即使是在语法上完全正确的语句,尝试执行它的时候,也有可能会发生错误。在程序运行中检测出的错误称之为<em>异常</em>,它通常不会导致致命的问题,你很快就会学到如何在 Python 程序中控制它们。大多数异常不会由程序处理,而是显示一个错误信息:<P><div class="verbatim"><pre>
&gt;&gt;&gt; 10 * (1/0)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
&gt;&gt;&gt; 4 + spam*3
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
NameError: name 'spam' is not defined
&gt;&gt;&gt; '2' + 2
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects</pre></div><P>The last line of the error message indicates what happened.
Exceptions come in different types, and the type is printed as part of
the message: the types in the example are
<tt class="exception">ZeroDivisionError</tt>, <tt class="exception">NameError</tt> and
<tt class="exception">TypeError</tt>.
The string printed as the exception type is the name of the built-in
exception that occurred.  This is true for all built-in
exceptions, but need not be true for user-defined exceptions (although
it is a useful convention).
Standard exception names are built-in identifiers (not reserved
keywords).<P>错误信息的最后一行指出发生了什么错误。异常也有不同的类型,异常类型做为错误信息的一部分显示出来:示例中的异常分别为 <tt class="exception">零除错误( ZeroDivisionError )</tt> ,<tt class="exception">命名错误( NameError)</tt> 和 <tt class="exception">类型错误(TypeError)</tt>。打印错误信息时,异常的类型作为异常的内置名显示。对于所有的内置异常都是如此,不过用户自定义异常就不一定了(尽管这是一个很有用的约定)。标准异常名是内置的标识(没有保留关键字)。<P>The rest of the line is a detail whose interpretation depends on the
exception type; its meaning is dependent on the exception type.<P>这一行后一部分是关于该异常类型的详细说明,这意味着它的内容依赖于异常类型。<P>The preceding part of the error message shows the context where the
exception happened, in the form of a stack backtrace.
In general it contains a stack backtrace listing source lines; however,
it will not display lines read from standard input.<P>错误信息的前半部分以堆栈的形式列出异常发生的位置。通常在堆栈中列出了源代码行,然而,来自标准输入的源码不会显示出来。<P>The <em class="citetitle"><a href="../lib/module-exceptions.html" title="Python Library
Reference" >Python Library
Reference</a></em> lists the built-in exceptions and their meanings.<P><em class="citetitle"><a href="../lib/module-exceptions.html" title="Python 库参考手册" >Python 库参考手册</a></em>列出了内置异常和它们的含义。<P><H1><A NAME="SECTION0010200000000000000000"></A><A NAME="handling"></A><BR>8.2 处理异常 Handling Exceptions </H1><P>It is possible to write programs that handle selected exceptions.
Look at the following example, which asks the user for input until a
valid integer has been entered, but allows the user to interrupt the
program (using <kbd>Control-C</kbd> or whatever the operating system
supports); note that a user-generated interruption is signalled by
raising the <tt class="exception">KeyboardInterrupt</tt> exception.<P>通过编程可以处理指定的异常。以下的例子重复要求用户输入一个值,直到用户输入的是一个合法的整数为止。不过这个程序允许用户中断程序(使用<kbd>Control-C</kbd> 或者其它操作系统支持的方法)。需要注意的是用户发出的中断会引发一个<tt class="exception">KeyboardInterrupt</tt> 异常。<P><div class="verbatim"><pre>
&gt;&gt;&gt; while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops! That was no valid number.  Try again..."
...</pre></div><P>The <tt class="keyword">try</tt> statement works as follows.<P><tt class="keyword">try</tt> 语句按如下方式工作:<P><UL><LI>First, the <em>try clause</em> (the statement(s) between the
<tt class="keyword">try</tt> and <tt class="keyword">except</tt> keywords) is executed.<P>首先,执行 <em>try</em> 子句(在 <tt class="keyword">try</tt> 和 <tt class="keyword">except</tt>
关键字之间的部分)。<P></LI><LI>If no exception occurs, the <em>except clause</em> is skipped and
execution of the <tt class="keyword">try</tt> statement is finished.<P>如果没有异常发生, <em>except 子句</em> 在 <tt class="keyword">try</tt> 语句执行完毕后就被忽略了。<P></LI><LI>If an exception occurs during execution of the try clause, the rest of
the clause is skipped.  Then if its type matches the exception named
after the <tt class="keyword">except</tt> keyword, the rest of the try clause is
skipped, the except clause is executed, and then execution continues
after the <tt class="keyword">try</tt> statement.<P>如果在 <tt class="keyword">try</tt>
子句执行过程中发生了异常,那么该子句其余的部分就会被忽略。如果异常匹配于 <tt class="keyword">except</tt> 关键字后面指定的异常类型,就执行对应的except子句,忽略try子句的其它部分。然后继续执行try语句之后的代码。<P></LI><LI>If an exception occurs which does not match the exception named in the
except clause, it is passed on to outer <tt class="keyword">try</tt> statements; if
no handler is found, it is an <em>unhandled exception</em> and execution
stops with a message as shown above.<P>如果发生了一个异常,在 except 子句中没有与之匹配的分支,它就会传递到上一级 <tt class="keyword">try</tt> 语句中。如果最终仍找不到对应的处理语句,它就成为一个未处理异常,终止程序运行,显示提示信息。<P></LI></UL><P>A <tt class="keyword">try</tt> statement may have more than one except clause, to
specify handlers for different exceptions.  At most one handler will
be executed.  Handlers only handle exceptions that occur in the
corresponding try clause, not in other handlers of the same
<tt class="keyword">try</tt> statement.  An except clause may name multiple exceptions
as a parenthesized list, for example:<P>一个 <tt class="keyword">try</tt> 语句可能包含多个 except 子句,分别指定处理不同的异常。至多只会有一个分支被执行。异常处理程序只会处理对应的 <tt class="keyword">try</tt> 子句中发生的异常,在同一个 <tt class="keyword">try</tt> 语句中,其他子句中发生的异常则不作处理。一个except子句可以在括号中列出多个异常的名字,例如:<P><div class="verbatim"><pre>
... except (RuntimeError, TypeError, NameError):
...     pass</pre></div><P>The last except clause may omit the exception name(s), to serve as a
wildcard.  Use this with extreme caution, since it is easy to mask a
real programming error in this way!  It can also be used to print an
error message and then re-raise the exception (allowing a caller to
handle the exception as well):<P>最后一个 except 子句可以省略异常名,把它当做一个通配项使用。一定要慎用这种方法,因为它很可能会屏蔽掉真正的程序错误,使人无法发现!它也可以用于打印一行错误信息,然后重新抛出异常(可以使调用者更好的处理异常)。<P><div class="verbatim"><pre>
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise</pre></div><P>The <tt class="keyword">try</tt> ... <tt class="keyword">except</tt> statement has an optional
<em>else clause</em>, which, when present, must follow all except
clauses.  It is useful for code that must be executed if the try
clause does not raise an exception.  For example:<P><tt class="keyword">try</tt> ... <tt class="keyword">except</tt> 语句可以带有一个 <em>else 子句</em>, 该子句只能出现在所有 except 子句之后。当 try 语句没有抛出异常时,需要执行一些代码,可以使用这个子句。例如:<P><div class="verbatim"><pre>
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -