try:
f = open(‘test.txt’)
print(f.read())
f.close()
except OSError as error:
print(‘打开文件出错\n原因是:’+str(error))
“”“try 下面的子句要是没有出错不会去执行except 发现异常则会执行except后面的语句”""
try:
int(“abc”)
s = 1+ ‘1’
f = open(‘test.txt’)
print(f.read())
f.close()
except OSError as error:
print(‘打开文件出错\n原因是:’ + str(error))
except TypeError as error:
print(‘类型出错\n原因是:’ + str(error))
except ValueError as error:
print(‘数值出错\n原因是:’ + str(error)
“”“一个try可以对应多个except 但是只有一个except会被执行”""
dict1 = {‘a’: 1, ‘b’: 2, ‘v’: 22}
try:
x = dict1[‘y’]
except LookupError:
print(‘查询错误!’)
except KeyError:
print(‘键错误!’)
else:
print(x)
try:
s = 1 + ‘1’
int(‘abc’)
f = open(‘tet.txt’)
print(f.read())
f.close()
except (OSError,TypeError,ValueError) as error:
print(‘出错了\n原因是:’ + str(error))
def divide(x,y):
try:
result = x/y
print('result is ', result)
except ZeroDivisionError:
print(‘division by zero!’)
finally:
print(‘excuting finally clause’)
print(divide(2,1)
print(divide(2,0))
print(divide(“2”,“1”))