Python自定义异常及抛出异常

 1 """
 2     自定义异常
 3 """
 4 class MyException(Exception): # 继承异常类
 5     def __init__(self, name, reason):
 6         self.name = name
 7         self.reason = reason
 8     
 9 from datetime import datetime
10 try:
11     if str(datetime.now()) > "2018":
12         raise MyException("TimeoutException", "time is overtime...")
13 except MyException as e:
14     print(e.name +":"+e.reason)
15     
16 """
17     抛出异常
18 """        
19 try:
20     6/0
21     raise
22 except Exception as e:
23     print(e)
 8 try:
 9     print("--------------")
10 except NameError as e: # 捕获NameError类型异常
11     print(e)
12 except Exception as e: # 捕获其它异常
13     print(e)
14 else:
15     print("没有异常会接着往下执行。。。")
16 finally:
17     print("最后一定执行。。。")
18    
19 # 测试捕获某种或某些种except
20 try:
21     print(aaa)
22     print("--------------") # 出现异常后不会执行下面的程序
23 except NameError as e: # 捕获NameError类型异常
24     print(e)
25 except Exception as e: # 捕获其它异常
26     print(e)
27 else:
28     print("没有异常会接着往下执行。。。")
29 finally:
30     print("最后一定执行。。。")
31 
32 # 测试捕获其它异常  
33 try:
34     open("a.txt")
35     print("--------------")
36 except NameError as e: # 捕获NameError类型异常
37     print(e)
38 except Exception as e: # 捕获其它异常
39     print(e)
40 else:
41     print("没有异常会接着往下执行。。。")
42 finally:
43     print("最后一定执行。。。")
44     
45 # 测试异常传递
46 def err():
47     print(aaa)
48     
49 try:
50     print("===============")
51     err()
52 except NameError as e: # 捕获NameError类型异常
53     print(e)
54     
55 print("use try will make your code beauty")

结果:

 

posted @ 2018-12-19 21:21  云山之巅  阅读(7014)  评论(0编辑  收藏  举报