Rioca

博客园 首页 新随笔 联系 订阅 管理

032异常处理

file_name=input('请输入需要打开的文件名:')
f=open(file_name)
print('文件的内容是:')
for each_line in f:
    print(each_line)

>>> my_list=['小甲鱼是帅哥']
>>> assert len(my_list)>0
>>> my_list.pop()
'小甲鱼是帅哥'
>>> assert len(my_list)>0
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(my_list)>0
AssertionError
>>> my_list.fishc
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
>>> my_list=[1,2,3]
>>> my_lsit[3]
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    my_lsit[3]
NameError: name 'my_lsit' is not defined
>>> my_list[2]
3
>>> my_dict={'one':1,'two':2,'three':3}
>>> my_dict['one']
1
>>> my_dict['two']
2
>>> my_dict['four']
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    my_dict['four']
KeyError: 'four'
>>> 1+'1'
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    1+'1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

033异常检测

  • try-except语句
    try:
    检测范围
    except Exception[as reason]:
    出现异常(Exception)后的处理代码
try:
    sum=1+'1'
    f=open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错啦,出错的原因是:'+str(reason))
except TypeError as reason:
    print('类型出错啦,出错的原因是:'+str(reason))
  • try-finally语句
    try:
    检测范围
    except Exception[as reason]:
    出现异常(Exception)后的处理代码
    finally:
    无论如何都会被执行的代码
try:
    f=open('我为什么是一个文件.txt','w')
    print(f.write('我存在了!'))
    sum=1+'1'
except (OSError,TypeError):
    print('文件出错啦')
finally:
    f.close()
  • raise语句
    可以在其中添加解释异常原因的语句
>>> raise ZeroDivisionError('除数为零的异常')
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    raise ZeroDivisionError('除数为零的异常')
ZeroDivisionError: 除数为零的异常
posted on 2020-09-07 16:41  Rioca  阅读(72)  评论(0编辑  收藏  举报