LinuxEye - Linux系统教程

LinuxEye - Linux系统教程

当前位置: 主页 > 脚本编程 >

Python 异常处理

时间:2013-10-30 11:33来源:blog.linuxeye.com 编辑:linuxeye 点击:
当你的程序中出现某些异常的状况的时候,异常就发生了。例如,当你想要读某个文件的时候,而那个文件不存在。或者在程序运行的时候,你不小心把它删除了。这些情况可以使用异
当你的程序中出现某些异常的状况的时候,异常就发生了。例如,当你想要读某个文件的时候,而那个文件不存在。或者在程序运行的时候,你不小心把它删除了。这些情况可以使用异常来处理。

假如你的程序中有一些无效的语句,会怎么样呢?Python会引发并告诉你那里有一个错误,从而处理这样的情况。

常见Python错误
AttributeError    视图访问一个对象没有的属性,比如foo.x,但是foo没有属性x
>>> a = (1,2,3)
>>> a.append(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
IOError    输入/输出异常;基本上是无法打开文件
>>> f = open('linuxeye.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'linuxeye.txt'
ImportError    无法引入模块和包;基本上市路径问题或者名称错误

IndentationError    语法错误(的子类);代码没有正确对齐

indexError    下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
>>> a = [1,2,3]
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
KeyError    视图访问字典里不存在的键
>>> dict = {1:'first',2:'second',3:'three'}
>>> dict[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4
KeyboardInterrupt   Ctrl+C被按下

NameError    使用一个还未被赋予对象的变量

SyntaxError    Python代码非法,代码不能编译(语法错误)

TypeError    传入对象类型与要求不相符

UnboundLocalError    视图访问一个还未被设置的局部变量,基本上是由于另有一个同样的全局变量导致你以为正在访问它

ValueError    传入一个调用者不期望的值,即使值得类型是正确的

try..except
把通常的语句放在try块中,而把我们的错误处理语句放在except块中
#!/usr/bin/env python
# Filename: try_except.py
import sys

try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit() # exit the program
except:
    print '\nSome error/exception occurred.'
    # here, we are not exiting the program

print 'Done'
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Learning Python
Done

引发异常
使用raise语句引发异常。你还得指明错误/异常的名称和伴随异常触发的异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类
#!/usr/bin/env python
# Filename: raising.py
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    s = raw_input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
    # Other work can continue as usual here
except EOFError:
    print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
    print 'ShortInputException: The input was of length %d, \
          was expecting at least %d' % (x.length, x.atleast)
else:
    print 'No exception was raised.'
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> py
ShortInputException: The input was of length 2,           was expecting at least 3
$ python raising.py
Enter something --> python
No exception was raised.

try ... finally
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。注意,在一个try块下,你可以同时使用except从句和finally块。如果你要同时使用它们的话,需要把一个嵌入另外一个
------分隔线----------------------------
标签:Python异常处理
栏目列表
推荐内容