try:
f =open('test.txt')print(f.read())
f.close()except OSError:print('打开文件出错')# 打开文件出错try:
f =open('test.txt')print(f.read())
f.close()except OSError as error:print('打开文件出错\n原因是:'+str(error))# 打开文件出错# 原因是:[Errno 2] No such file or directory: 'test.txt'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))# 数值出错# 原因是:invalid literal for int() with base 10: 'abc'
dict1 ={'a':1,'b':2,'v':22}try:
x = dict1['y']except LookupError:print('查询错误')except KeyError:print('键错误')else:print(x)# 查询错误
dict1 ={'a':1,'b':2,'v':22}try:
x = dict1['y']except KeyError:print('键错误')except LookupError:print('查询错误')else:print(x)# 键错误
except 子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。
try:
s =1+'1'int("abc")
f =open('test.txt')print(f.read())
f.close()except(OSError, TypeError, ValueError)as error:print('出错了!\n原因是:'+str(error))# 出错了!# 原因是:unsupported operand type(s) for +: 'int' and 'str'