第八天:错误异常处理

错误类型

1、语法错误

SyntaxError:代码拼写出错
AttributeError:属性异常

try:
    x = 5 / 0
    print(x)
except ZeroDivisionError:
    print('不能除零')
except:
    print('其他错误')
else:
    print('没有异常')

2、语义错误

3、逻辑错误

二、异常处理

1、try:有可能出现异常代码

2、except:异常类型 as 实例:捕获特定异常

3、finally:不论是否遇到异常均会执行

class Person:
    def __init__(self,name):
        self.name = name
f = open('hello.txt')
p = Person('Peter')
try:
    f.read()
except:# 捕获异常
    print('文件操作遇到错误!')
finally:#不管有没异常,这一步都要执行
    f.close()

4、else:未遇到异常时

5、raise:手动抛出异常

def mothod():
    raise NotImplementedError('该方法代码还未实现')
mothod()
原文地址:https://www.cnblogs.com/linyk/p/11482084.html