学习-Python异常处理之try…except…finally…

第1关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 请在下面的 Begin-End 之间按照注释中给出的提示编写正确的代码
########## Begin ##########
f = open("src/step1/test.txt","r")
try:
    eval(input())
except Exception as e:
    print(f"错误信息为{e}")
finally:
    f.close()
########## End ##########
if f.closed:
    print("文件已关闭")
else:
    print("文件未关闭")

Python异常处理

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

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
class MyError(Exception):
    #********begin*********#
    def __init__(self,number):
        Exception.__init__(self)
        self.number=number
    def __str__(self):
        return '这是我定义的第%d个异常' %(self.number)
    #******** end*********#

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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*********#