#异常处理
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!')