运行的异常处理

#异常处理
a=int(input('fenzi'))
b=int(input('fenmu'))
try:
    print(a/b)
except Exception as thing:
    print('what\'s wrong with you')
    print(f'Wrong!Exactly:{thing}')
else:
    print('that is not a big deal')
#指定异常 如:
    except ZeroDivisionError 
#finally最终值行,else顺利值行
try:
    x=open('thing.txt','r')
except:
    x=open('thing.txt','w')
else:
    print('No wrong, good job!')
finally:
    x.close()
#with as 打开文件不用手动关闭
try:
    with open('thing.txt','r') as x:
        for i in x:
            print(i)
except OSError as thing:
    print(f'{thing}')
#嵌套
import time
try:
    file=open('abc.txt')
    
    try:
        while True:
            content=file.readlines()
            if len(content)==0:
                break
            time.sleep(2)
            print(content)
    except:
        print('Something Wrong')
    finally:
        file.close()
        print('close the file')
except:
    print('no file exist')

#自定义异常 不满足要求的报错
class password(Exception):
    def __init__(self,length,minlen):
        self.length=length
        self.minlen=minlen
    def __str__(self):
        return f'the length you inputted is {self.length},can\'t be less than {self.minlen}'
def bymyself():
    try:
        x=input('please input your password')
        if len(x)<8:
            raise password(len(x),8)
    except Exception as thing:
        print(thing)
    else:
        print('completed!')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值