第1关:Python异常类与自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- coding: utf-8 -*-

class MyError(Exception):
#********begin*********#
id = 0

def __init__(self, id):
Exception.__init__(self)
self.id = id

def __str__(self):
return f"这是我定义的第{self.id}个异常"



#******** end*********#

第2关:Python中的异常处理结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MyError(Exception):
def __str__(self):
return "长度过长,大于3"


def TestLength(x):
x = len(x)
# *********begin*********#
try:
if x > 3:
raise MyError(x)

except MyError as e:
print(e)
else:
print("长度合适")

finally:
print("执行完毕")

# ********* end*********#