处理Python中的异常(Python)


处理Python中的异常

1. 处理FileNotFoundError异常

使用文件时,一种常见的问题是找不到文件:你要查找的文件可能在其他地方、文件名可能不正确或者这个文件根本就不存在。

错误案例

例如当前目录下没有文件helloworld.txt,但还是要打开它,程序运行异常

with open (filename, 'r') as f:  # 以读的方式打开文件helloworld.txt,并返回文件句柄给变量f
        readbuf = f.read ()      # 读取文件helloworld.txt
        print (readbuf)          # 打印读取内容

解决方法

filename = "helloworld.txt"
try:
    with open (filename, 'r') as f:  # 以读的方式打开文件helloworld.txt,并返回文件句柄给变量f
        readbuf = f.read ()          # 读取文件helloworld.txt
        print (readbuf)              # 打印读取内容
except FileNotFoundError:
    msg = "Sorry, the file " + filename + "does not exist."
    print (msg)

2. 处理ZeroDivisionError异常

整数除法运算,除数是不能为0

错误案例

print (5/0)

解决方法

try:
    print (5/0)
except ZeroDivisionError:
    print ("division by zero.")

3. try-except代码块的使用

当你认为可能发生错误时,可编写一个try-except代码块来处理可能引发的异常。