python基础篇-异常
python异常的标准格式:
try:
    dosomething() //可能出现逻辑错误的地方
except Excepthon as result:  //异常信息str
    print(result)  //发生异常要执行的代码
else:
    doRightthing() //未捕获异常要执行的代码
finally:
    do_must_doings()  //必然要执行的代码,比如f.close()
ps: Exceotion 可以不写,也可以指定异常,如NameError
ps:TraceBack的最后,前半部分为指定异常的类型,后接一次的_str_()

ps: 一般try下方只放一行左右的指定尝试执行的代码
ps:捕获多个指定异常,异常放在元组中
excetp (NameError,ZeroDivisionError):
ps:Exception 或者不写 捕获所有异常,Exception是所有异常类的基类
ps:异常的传递
异常可以嵌套,从外而内
import time
 
try:
    f.open('demo.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break;
            time.sleep(2)
            print(content)
    except   Exception:
        print('读取错误')
except:
    print('文件打开出错')
自定义异常: 自定义异常类--抛出异常 -- 捕获异常
class ShortInputError(Exception):
    def _init_(self, str, len = 8):
        self.str = str
        self.len = len
    def _str_(self):
        return f'输入字符{self.str}的长度 {len(self.str)},小于指定长度{self.len}'
def main():
    try:
        con  = input('请输入:')
        if len(con) < 8:
            raise ShortInputError(con) //raise关键字抛出异常
    except ShortInputError as result:
        print(result)
    else:
        print('有效输入')
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号