异常处理中抛出异常
class Test(object):
def __init__(self,switch):
self.switch=switch
def calc(self,a,b):
try:
return a/b
except ZeroDivisionError as result:
if self.switch:
print('the exception already open , catch the info is',result)
else:
raise
a=Test(True)
a.calc(11,0)
a.switch=False
a.calc(11,0)
抛出自定义的异常 raise语句来引发自定义的异常
定义输出的长度 属性中有长度和至少输出的长度
class ShortInputException(Exception):
def __init__(self,length,least):
# super__init__()
# 建议填写super这一项调用父类的方法 之后再添加自己的功能
self.length=length
self.least=least
# 主函数中输入信息 并且进行判断之后进行抛异常
def main():
try:
s=input('please input the num or word ----->')
if len(s)<3:
raise ShortInputException(len(s),3)
except ShortInputExceptionas result:
print('ShortInputException : input the length is %s, the lenth of atleast is %s' % (result.length,result.atleast))
else:
print('no exception happending ! ! !')
main()
嵌套函数抛出异常
def test1():
print('***** test1 *****')
print(num)
print('***** test2 *****')
def test2():
print(' ***** test3 ***** ')
open('a.txt')
print(' ***** test4 ***** ')
def test3():
try:
print(' ***** test5 - 1 *****')
test1()
test2()
print(' ***** test5 -2 *****')
except Exception as result:
print('catch the exception ! ! !',result)
test3()
网友评论