首页 > 其他 > 详细

学习心得2020.08.30

时间:2020-09-07 17:28:01      阅读:57      评论:0      收藏:0      [点我收藏+]

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: 除数为零的异常

学习心得2020.08.30

原文:https://www.cnblogs.com/rioca/p/13627700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!