-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathpython-error-and-exception.py
More file actions
137 lines (93 loc) · 2.8 KB
/
Copy pathpython-error-and-exception.py
File metadata and controls
137 lines (93 loc) · 2.8 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###基类###
class BException(Exception): #继承Exception基类
pass
class CException(BException): #继承BException基类
pass
class DException(CException): #继承CException基类
pass
for cls in [BException, CException, DException]:
try:
raise cls() #抛出异常
except DException:
print("D")
except CException:
print("C")
except BException:
print("B")
###不带异常类型的 except###
try:
raise BException() #抛出异常
except DException:
print("D")
except:
print("处理全部其它异常") #处理全部其它异常
try:
raise BException() #抛出异常
except (BException, DException):
print("D")
except:
print("处理全部其它异常") #处理全部其它异常
else:
print("没有异常发生") #没有异常发生
try:
raise BException() #抛出异常
except (BException, DException):
print("D")
except:
print("处理全部其它异常") #处理全部其它异常
else:
print("没有异常发生") #没有异常发生
finally:
print("你们绕不过我,必须执行") #必须执行的代码
###异常的参数###
try:
x = 1 / 0 # 除数为0
except ZeroDivisionError as err: #为异常指定变量err
print("Exception")
print(err.args) #打印异常的参数元组
print(err) #打印参数,因为定义了__str__()
###触发异常###
def diyException(level):
if level > 0:
raise Exception("raise exception", level) #主动抛出一个异常,并且带有参数
print('我是不会执行的') #这行代码不会执行
try:
diyException(2) #执行异常方法
except Exception as err: #捕获异常
print(err) #打印异常参数
#定义函数
def diyException(level):
if level > 0:
raise Exception("error level", level) #主动抛出一个异常,并且带有参数
print('我是不会执行的') #这行代码不会执行
try:
diyException(2) #执行异常方法
except 'error level' as err: #捕获异常
print(err) #打印异常参数
import traceback
#定义函数
def diyException(level):
if level > 0:
raise Exception("error level", level) #主动抛出一个异常,并且带有参数
print('我是不会执行的') #这行代码不会执行
try:
diyException(2) #执行异常方法
except Exception: #捕获异常
traceback.print_exc()
###用户自定义异常###
#自定义异常
class DiyError(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise DiyError("my diy exception") #触发异常
except DiyError as e:
print(e)
###预定义的清理行为###
for line in open("myfile.txt"):
print(line, end="")
with open("myfile.txt") as f:
for line in f:
print(line, end="")