The Python Tutorial 8——Errors and Exceptions

来源:互联网 发布:小号手模型淘宝旗舰店 编辑:程序博客网 时间:2024/05/24 07:04

两类错误:语法或者是逻辑  syntax errors and exceptions.

8.1. Syntax Errors

>>> while True print 'Hello world'  File "<stdin>", line 1, in ?    while True print 'Hello world'                   ^SyntaxError: invalid syntax
The parser repeats the offending line and displays a little ‘arrow’ pointing atthe earliest point in the line where the error was detected. The error is caused by (or at least detected at) the tokenpreceding the arrow: in the example, the error is detected at the keywordprint, since a colon(':') is missing before it. File name and line number are printed so youknow where to look in case the input came from a script.

8.2. Exceptions

Even if a statement or expression is syntactically correct, it may cause anerror when an attempt is made to execute it. Errors detected during executionare calledexceptions and are not unconditionally fatal: you will soon learnhow to handle them in Python programs.
>>> 10 * (1/0)Traceback (most recent call last):  File "<stdin>", line 1, in ?ZeroDivisionError: integer division or modulo by zero>>> 4 + spam*3Traceback (most recent call last):  File "<stdin>", line 1, in ?NameError: name 'spam' is not defined>>> '2' + 2Traceback (most recent call last):  File "<stdin>", line 1, in ?TypeError: cannot concatenate 'str' and 'int' objects

8.3. Handling Exceptions

异常处理使用try  except语句

>>> while True:...     try:...         x = int(raw_input("Please enter a number: "))...         break...     except ValueError:...         print "Oops!  That was no valid number.  Try again..."...

The try statement works as follows. 处理流程

  • First, the try clause (the statement(s) between the try andexcept keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of thetry statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause isskipped. Then if its typematches the exception named after theexcept keyword, the except clause is executed, and then execution continues after thetry statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outertry statements; if no handler isfound, it is anunhandled exception and execution stops with a message as shown above.

A try statement may havemore 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 sametry statement. An except clause mayname multiple exceptions as a parenthe sizedtuple, for example:

... except (RuntimeError, TypeError, NameError):...     pass

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):

import systry:    f = open('myfile.txt')    s = f.readline()    i = int(s.strip())except IOError as e:    print "I/O error({0}): {1}".format(e.errno, e.strerror)except ValueError:    print "Could not convert data to an integer."except:    print "Unexpected error:", sys.exc_info()[0]    raise
The try ...except statement has an optionalelse clause, which, when present,must follow all except clauses. It is useful for code thatmust be executed if the try clause does not raise an exception. Forexample:
for arg in sys.argv[1:]:    try:        f = open(arg, 'r')    except IOError:        print 'cannot open', arg    else:        print arg, 'has', len(f.readlines()), 'lines'        f.close()

8.4. Raising Exceptions

The raise statement allows the programmer to force a specifiedexception to occur. For example:

>>> raise NameError('HiThere')Traceback (most recent call last):  File "<stdin>", line 1, in ?NameError: HiThere

The sole argument to raise indicates the exception to be raised.This must be either anexception instance or an exception class (a class thatderives from Exception).

8.5. User-defined Exceptions

用户可以通过继承Exception类定义自己的异常类

>>> class MyError(Exception):...     def __init__(self, value):...         self.value = value...     def __str__(self):...         return repr(self.value)...>>> try:...     raise MyError(2*2)... except MyError as 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!'

Most exceptions are defined with names that end in “Error,” similar to the naming of the standard exceptions.

8.6. Defining Clean-up Actions

A finally clause is always executed before leaving thetry statement, whether an exception has occurred or not. finally语句总会执行,如果出现except语句未处理的异常则重新抛出异常。

>>> def divide(x, y):...     try:...         result = x / y...     except ZeroDivisionError:...         print "division by zero!"...     else:...         print "result is", result...     finally:...         print "executing finally clause"...>>> divide(2, 1)result is 2executing finally clause>>> divide(2, 0)division by zero!executing finally clause>>> divide("2", "1")executing finally clauseTraceback (most recent call last):  File "<stdin>", line 1, in ?  File "<stdin>", line 3, in divideTypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the finally clause is executed in any event. TheTypeError raised by dividing two strings is not handled by theexcept clause and thereforere-raised after the finally clause has been executed.

In real world applications, the finally clause is useful forreleasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

try:    f = open('xxx')except:    print 'fail to open'    exit(-1)try:    do somethingexcept:    do somethingfinally:    f.close()
参照点击打开链接

8.7. Predefined Clean-up Actions

with open("myfile.txt") as f:    for line in f:        print line,
with  as 语句  Python特有  可参照上面的链接


0 0