18. 异常

18.1. 内建异常

 1>>> import exceptions
 2>>> dir(exceptions)
 3['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning',
 4'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning',
 5'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
 6'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError',
 7'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning',
 8'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',
 9'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
10'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',
11'__doc__', '__name__', '__package__']

所有异常的基类:Exception

18.2. 引发异常

 1>>> from exceptions import *
 2
 3>>> raise KeyError
 4Traceback (most recent call last):
 5  File "<input>", line 1, in <module>
 6KeyError
 7
 8>>> raise Exception
 9Traceback (most recent call last):
10  File "<input>", line 1, in <module>
11Exception
12
13>>> raise Exception("stack overflow")
14Traceback (most recent call last):
15  File "<input>", line 1, in <module>
16Exception: stack overflow

18.3. try 语句块

 1try:
 2  # 运行代码
 3  # 可能引发异常
 4except exception:
 5## 多个异常:except (exception1, exception2,...)
 6  # 处理异常
 7else:
 8  # 如果没有异常发生
 9finally:
10## 无论是否发生异常都将执行最后的代码
11  # 最终的清理工作,如:关闭文件

例子:

1try:
2  fh = open("testfile", "w")
3  fh.write("这是一个测试文件,用于测试异常!!")
4except IOError:
5  print "Error: 没有找到文件或读取文件失败"
6else:
7  print "内容写入文件成功"
8finally:
9  fh.close()

18.4. 捕捉对象

try:
  # 运行代码
  # 可能引发异常
except exception, e: ## e 是一个异常对象
## python3: except exception as e
  # 处理异常
  print e

例子:

 1>>> def foo():
 2...   try:
 3...     x = input('Enter the first number: ')
 4...     y = input('Enter the second number: ')
 5...     print x / y
 6...   except (ZeroDivisionError, TypeError), e:
 7...     print e
 8
 9>>> foo()
10Enter the first number: >? 1
11Enter the second number: >? 0
12integer division or modulo by zero
13
14>>> foo()
15Enter the first number: >? 1
16Enter the second number: >? 'b'
17unsupported operand type(s) for /: 'int' and 'str'

18.5. 全捕捉

1try:
2  # 运行代码
3  # 可能引发异常
4except:
5  # 处理异常

捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。

可以使用:

1try:
2  # 运行代码
3  # 可能引发异常
4except Exception, e:
5  # 处理异常
6  print e

Note

如果 estr(e) 打印出来都是空白,可以尝试打印 repr(e) ,或者:

import traceback
traceback.print_exc() ## 在需要打印异常的地方

18.6. 参考资料

  1. Python 异常处理