六、Python:异常

king's blog

下面我们通过几个例子,大概了解下python的异常的种类,比如文件不存在,语法错误等,及捕如何获异常等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#1、当未捕获到异常时,执行else语句
try:
    f=file("a.txt","r")
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print line
    else:
        print "read end!",
    f.close()
except IOError:
    print "file is't exist!"
except Exception:
    print "have error!"
else:
    print "all is ok"
   
#例子1:捕捉所有异常  
a = 3
b = 4
c = 5

try:
    a=b
    b=c
except Exception ,data :
    print Exception ,":",data
   
   
#例子2:采用traceback模块查看异常,需要导入traceback模块
import sys
try:
    a = b
    b = c
except:
    import traceback
    print traceback.print_exc()
   
#例子3:采用sys模块回溯最后的异常
try:
    a = b
    b = c
except:
    info = sys.exc_info()
    print len(info)
    print info
    print info[0]
    print info[1]

#例子4:finally 语句,不管有没有发生异常都将执行finally语句块。
try:
    a= 3/1
finally:
    print "exec finally"
   
#例子5:try-except-finally
import sys
try:
    a=3/0
except ZeroDivisionError:
    print 'error'
finally:
    print "stop exec"

try:
    a=5/0
except:
    print sys.exc_info()[1]
finally:
    print "stop exec"

#例6:引发异常
class MyError( Exception ):
    pass

try:
    raise MyError     #自己抛出一个异常
except MyError:
    print 'a error'

输出:

1
2
3
4
5
6
7
file is't exist!
exec finally
error
stop exec
integer division or modulo by zero
stop exec
a error
Tags:
文 / 甲乙丙丁
LEAVE A REPLY

loading