1. 异常引入之ZeroDividionError
# _*_ coding:utf8 _*_
# 处理ZeroDivisionError
# print(5/0)
# print('zhi is my dream')
# 用 try-except 来处理异常
# try:
# # 放要处理的语句
# print(5/0)
# # 要处理的异常
# except ZeroDivisionError:
# # 针对该异常提示什么或者做什么操作
# print(" zero is not")
# # 正常执行该语句
# print(' this is my dream')
# 使用异常避免崩溃 else代码块
print("give me two number,and i will divison them")
print("Enter q is quit")
while True:
first = input("please input your first number ")
if first == 'q':
break
second = input('please input your second number')
if second == 'q':
break
try:
# 可能出现异常的放在try当中
num = int(first)/int(second)
except ZeroDivisionError:
print("no no no no ")
else:
# 需要try中代码执行没有问题再去执行,就放在else中
print(str(num))
2. FileNotFoundError
# 处理FileNotFoundError
file_name = 'alice.txt'
# with open(file_name) as file_object:
# # 此处将会引发 FileNotFoundError
# contents = file_object.read()
# 使用try-except
# 这个错误是 open()函数抛出的 所以try中要包含 open()
with open(file_name, 'w') as file_object:
file_object.write(" i like you")
try:
with open(file_name) as file_object:
content = file_object.read()
print(content)
except FileNotFoundError:
print("文件没有找到")
else:
# 以空格为分隔符,将读取到字符串分割,到列表中,赋值给变量contents
contents = content.split()
# 打印列表
print(contents)
# 获取到列表的长度
print(len(contents))
# pass 语句:发生错误的时候,不会出现traceback和任何自定义的输入,(except中的)
# pass 还可以充当占位符,提醒你在程序的某个地方什么也没有做。