#异常处理的语法:try:
# 可能出现错误的代码块
# except:
# 出错后执行的代码(指定类型捕获异常)
# else:
# 没有出错的代码块
# finally:
# 不管有没有出错都执行的代码块
try:
# print(b)
a=1/0
pass
except NameError as kd:
print(kd)
pass
except Exception as msg: #能捕获所有出现的错误类型
print(msg)
pass
finally:
print('初次接触异常')
#自定义异常
# class LeNumException(Exception):
# def __str__(self):
# return '出现错误'
# try:
# num=int(input('请输入一个数字:'))
# if num<0:
# raise LeNumException()
# except LeNumException as e:
# print(e)
# else:
# print('没有出现异常')
class ToolongMyException(Exception):
def __init__(self,leng):
self.len=leng
pass
def __str__(self):
return '输入的长度为'+str(self.len)+',超过长度'
pass
def name_Test():
name=input('请输入你的姓名:')
if len(name)>4:
raise ToolongMyException(len(name))
else:
print(name)
pass
pass
name_Test()
运行结果