用户自己引发的异常处理
# 由用户自行定义的异常类处理
# 代码
# encoding = UTF-8
# 用户自己引发异常
class ShortInputException(Exception):
'''一个由用户定义的异常类'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter someting -->')
if len(text) < 3:
raise ShortInputException(len(text), 3)
# 其他工作能够在此处正常运行
except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print(('ShortInputException: The input was ' +
'{0} long,expected at least {1}')
.format(ex.length, ex.atleast))
else:
print('No exception was raised.')
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 运行结果
1.如果输入超过了3位数,截获错误
Enter someting -->88888
No exception was raised.
1
2
2
1
2
2
2.如果输入没有超过3位数
Enter someting -->12
ShortInputException: The input was 2 long,expected at least 3
1
2
2
1
2
2
编辑 (opens new window)
上次更新: 2022/12/31, 16:52:27
- 01
- SpringCache基本配置类05-16
- 03
- Rpamis-security-原理解析12-13