Python异常处理,:'Eclipse'


1.异常处理

异常:在运行代码过程中遇到的任何错误,大有error字样的都为异常

异常处理:对代码中所有可能会出现的异常进行处理

疑问:我们为什么要处理异常?

2.异常代码

import os
#创建一个已存在的文件夹
os.mkdir("Eclipse") #异常:FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'Eclipse' 

3.捕获指定异常

import os
try:#捕获异常
    #创建一个已存在的文件夹
    os.mkdir("Eclipse") #异常:FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'Eclipse'
except FileExistsError:#处理指定异常
    print("已捕获异常,在这里处理...")

4.捕获全部异常

第二种:

import
os try:#捕获异常 #创建一个已存在的文件夹 os.mkdir("Eclipse") #异常:FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'Eclipse' except:#只要有异常就处理 print("已捕获异常,在这里处理...")
第二种:

import os
try:#捕获异常
    #创建一个已存在的文件夹
    os.mkdir("Eclipse") #异常:FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'Eclipse'
except Exception:#只要有异常就处理
    print("已捕获异常,在这里处理...")

5.捕获异常并处理

import os

try:
    os.mkdir("Eclipse")
except Exception as e:
    print("捕获一个异常:{0}".format(e))
    file = open("eror.txt","a",encoding="utf8")
    file.write("\n"+str(e))
    file.close()

6.try...except...finally

#finally 不管是否有异常都执行

#try...except...finally
import os
try:
    os.rmdir("Arr/Brr")#删除一个不存在的路径
except Exception as e:
    print("处理异常:{0}".format(e))#处理异常:[WinError 3] 系统找不到指定的路径。: 'Arr/Brr'
finally:
    print("不管是否报错都执行")
#try...except...else

7.try...except...else

#else 不报异常执行

#try...except...else
import os
try:
    os.rmdir("Arr/Brr")#删除一个不存在的路径
except Exception as e:
    print("处理异常:{0}".format(e))#处理异常:[WinError 3] 系统找不到指定的路径。: 'Arr/Brr'
else:
    print("不报异常执行")

 

相关内容

    暂无相关文章

评论关闭