python_day6.3

一:异常

1.常用的异常:
AssertionError   断言语句assert失败
>>> mylist=['小甲鱼是帅哥']
>>> assert len(mylist)>0
>>> mylist.pop()
'小甲鱼是帅哥'
>>> assert len(mylist)>0
Traceback (most recent call last):
  File "<pyshell#120>", line 1, in <module>
    assert len(mylist)>0
AssertionError
>>> mylist.wwq
Traceback (most recent call last):
  File "<pyshell#121>", line 1, in <module>
    mylist.wwq
AttributeError: 'list' object has no attribute 'wwq'
AttributeError  尝试访问未知的对象属性
IndexError 索引超出序列的范围
keyError 字典中查找一个不存在的关键字
2.异常处理
try... except...的方法:
try:
    f=open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except:#不推荐这种做法print('出错了!')
try:
    f=open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错了!
错误的原因是:'+str(reason))

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:
    sum=1+'1'
    f=open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except (OSError,TypeError):
    print('出错了!')
View Code

try...except...finally 的方法

 finally后面是无论如何都会执行的语句

try:
    f=open('news.txt','w')
    print(f.write('我存在了'))
    sum=1+'1'
except(OSError,TypeError):
    print('出错啦')
finally:
    f.close()

3.raise语句引出异常

 二: else语句
1.else语句和if语句搭配
2.else和while搭配

 def showMaxFactor(num):
    count=num//2 #//的意思是除后取整
    while count>1:
        if num%count==0:
            print('%d最大的约数是%d' %(num,count))
            break
        count-=1
    else:
        print('%d是素数'% num)
num=int(input('请输入一个数'))
showMaxFactor(num)
View Code

3.和异常一起使用

try:
    int('124')
except ValueError as reason:
    print('出错啦'+str(reason))
else:
    print('没有任何异常')

三:with语句

try:
   with  open('data.txt','w') as f:
       for eachline in f:
           print(eachline)
except OSError as reason:
    print('出错啦'+str(reason))
原文地址:https://www.cnblogs.com/wwq1204/p/10698890.html