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 datetime10 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/021 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 # 测试捕获某种或某些种except20 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\")
结果:
因篇幅问题不能全部显示,请点此查看更多更全内容