python异常处理

总结

  • try中发生异常,执行except
  • try中不发生异常,执行else
  • try中的异常会阻止try接下来的所有操作
  • try中的return会阻止else的执行
  • 任何return都不会阻止finally的执行
 1 def except_no_return():
 2     """
 3     try中发生异常,执行except
 4     输出:in try-in except-in finally-None
 5     :return: 
 6     """
 7     try:
 8         print('in try')
 9         a = 1/0
10     except ZeroDivisionError:
11         print('in except')
12     else:
13         print('in else')
14     finally:
15         # 返回这个
16         print('in finally')
17 
18 
19 def else_no_return():
20     """
21     try中不发生异常,执行else
22     输出:in try-in else-in finally-None
23     :return: 
24     """
25     try:
26         print('in try')
27     except ZeroDivisionError:
28         print('in except')
29     else:
30         print('in else')
31     finally:
32         # 返回这个
33         print('in finally')
34 
35 
36 def try_except_finally():
37     """
38     try中的异常会阻止try接下来的所有操作
39     输出:in try-in else-in finally-return in finally
40     :return: 
41     """
42     try:
43         print('in try')
44         a = 1/0
45         return "return in try"
46     except ZeroDivisionError:
47         print('in except')
48         return "return in except"
49     else:
50         print('in else')
51         return "return in else"
52     finally:
53         # 返回这个
54         print('in finally')
55         return "return in finally"
56 
57 
58 def try_finally():
59     """
60     try中的return会阻止else的执行
61     输出:in try-in finally-return in finally
62     :return: 
63     """
64     try:
65         print('in try')
66         return "return in try"
67     except ZeroDivisionError:
68         print('in except')
69         return "return in except"
70     else:
71         print('in else')
72         return "return in else"
73     finally:
74         # 返回这个
75         print('in finally')
76         return "return in finally"
77 
78 
79 def try_else_finally():
80     """
81     任何return都不会阻止finally的执行
82     输出:in try-in else-in finally-return in finally
83     :return: 
84     """
85     try:
86         print('in try')
87     except ZeroDivisionError:
88         print('in except')
89         return "return in except"
90     else:
91         print('in else')
92         return "return in else"
93     finally:
94         # 返回这个
95         print('in finally')
96         return "return in finally"

 

posted @ 2018-06-14 11:02  huapyuan  阅读(219)  评论(0编辑  收藏  举报