File tree Expand file tree Collapse file tree 1 file changed +83
-0
lines changed
Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ '练习错误处理'
5+
6+ __author__ = 'sergiojune'
7+ import logging
8+ from functools import reduce
9+
10+
11+ def foo (n ):
12+ # 自定义抛出错误
13+ if n == 0 :
14+ raise ZeroDivisionError ('被除数不能为零' )
15+ return 10 / n
16+
17+
18+ print (foo (20 ))
19+ # 这个就会出错
20+ # print(foo(0))
21+
22+
23+ # 捕捉错误
24+ try :
25+ n = input ('请输入一个数字' )
26+ n = int (n )
27+ res = 10 / n
28+ print (res )
29+ # 有多种异常情况,所以有多个except语句块
30+ except ZeroDivisionError as e :
31+ print (e )
32+ except ValueError as e :
33+ # 用这个记录错误,开发中会发在日志上查看
34+ logging .exception (e )
35+
36+ # 当没有发生错误时会执行
37+ else :
38+ print ('成功运行' )
39+ # 这个语句块是必须执行的
40+ finally :
41+ print ('代码执行完毕' )
42+
43+ print ('end' )
44+
45+
46+ # 还可以自己创建异常
47+ # 只需要继承自某一个异常就可以了,不过一般不需要自定义异常
48+ class FooException (BaseException ):
49+ pass
50+
51+
52+ # 作业:运行下面的代码,根据异常信息进行分析,定位出错误源头,并修复
53+ def str2num (s ):
54+ try :
55+ return int (s )
56+ except ValueError as e :
57+ logging .exception (e )
58+ print ('捕捉成功' )
59+ try :
60+ return float (s )
61+ except ValueError as e :
62+ print (e )
63+ print ('输入的内容不是数字' )
64+
65+
66+ def calc (exp ):
67+ try :
68+ ss = exp .split ('+' )
69+ ns = map (str2num , ss )
70+ return reduce (lambda acc , x : acc + x , ns )
71+ except TypeError as e :
72+ print (e )
73+
74+
75+ def main ():
76+ r = calc ('100 + 200 + 345' )
77+ print ('100 + 200 + 345 =' , r )
78+ r = calc ('99 + 88 + 7.6' )
79+ print ('99 + 88 + 7.6 =' , r )
80+
81+
82+ main ()
83+ print ('end' )
You can’t perform that action at this time.
0 commit comments