The Python Tutorial 8——Errors and Exceptions

两类错误:语法或者是逻辑  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 token preceding the arrow: in the example, the error is detected at the keyword print, 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 called exceptions 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*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (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 the except 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 sys

try:
    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 optional else clause, 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. 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 an exception 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 the try 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 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.

In real world applications, the finally clause is useful for releasing 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 something
except:
    do something
finally:
    f.close()
参照 点击打开链接

8.7. Predefined Clean-up Actions

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值