简明Python教程学习笔记9

13、异常

(1)错误

程序中的一些无效语句,比如语法错误,如下所示:

1 >>> Print "aa"
2 SyntaxError: invalid syntax
3 >>> print "aa"
4 aa
5 >>> 

(2)try...except

1 >>> s = raw_input("Enter something -->")
2 Enter something -->#这里期望输入,但是实际执行了ctrl+d,导致了下面的异常
3 
4 Traceback (most recent call last):
5   File "<pyshell#4>", line 1, in <module>
6     s = raw_input("Enter something -->")
7 EOFError: EOF when reading a line
8 >>> 

可以使用try...except来处理异常

 1 # -*- coding:utf-8 -*-
 2 
 3 import sys
 4 
 5 try:
 6     s = raw_input("Enter something -->")
 7 except EOFError:
 8     print "\nWhy did yo do an EOF on me?"
 9     sys.exit()  # Exit the program
10 except:
11     print "\nSome error/exception occurred."
12     # here, we are not exiting the program
13 
14 print "Done"

输出:

(3)引发异常

可以使用raise语句 引发 异常

还得指明错误/异常的名称和伴随异常 触发的 异常对象。

可以引发的错误或异常应该分别是一个ErrorException类的直接或间接导出类。

 1 # -*- coding:utf-8 -*-
 2 
 3 
 4 class ShortInputException(Exception):
 5     """A user-defined exception class."""
 6 
 7     def __init__(self, length, atleast):
 8         Exception.__init__(self)
 9         self.length = length
10         self.atleast = atleast
11 
12 
13 try:
14     s = raw_input("Enter something -->")
15     if len(s) < 3:
16         raise ShortInputException(len(s), 3)
17         # other work can continue as usual here
18 except EOFError:
19     print "\nWhy did you do an EOF on me?"
20 except ShortInputException, x:
21     print "ShortInputException:The input was of length %d,was expecting at least %d" % (x.length, x.atleast)
22 else:
23     print "No exception was raised."

输出:

(4)try...finally

希望在无论异常发生与否的情况下都执行某些操作,该怎么做呢?

这可以使用finally块来完成。

 

posted @ 2018-02-01 09:35  七甲八甲  阅读(191)  评论(0编辑  收藏  举报