博客
关于我
python基础篇(8):异常处理
阅读量:797 次
发布时间:2023-03-07

本文共 2699 字,大约阅读时间需要 8 分钟。

Python异常处理详解

在Python编程中,异常是程序运行时可能遇到的错误事件,它会中断程序的正常执行流程。通过对异常的处理,可以使程序在遇到错误时能够采取适当措施,从而避免程序崩溃。

1. 错误类型

在编写Python代码时,错误主要分为两类:语法错误和异常错误。

  • 语法错误:这是由于代码不符合Python语法规范导致的错误,例如代码格式错误、缩进错误等。这些错误会阻止程序正常执行。

  • 异常错误:即使代码语法正确,程序在执行过程中也可能遇到错误。常见的异常错误包括:

    • zeroDivisionError:除零错误。
    • IndexError:索引越界错误。
    • KeyError:字典中键不存在。
    • SyntaxError:语法错误。
    • OSError:操作系统异常,如文件操作失败。
    • keyboardInterrupt:用户输入中断错误(如按下Ctrl+c)。
    • RuntimeError:运行时错误。
    • Exception:所有异常的父类。

通过捕获这些异常,可以让程序在遇到错误时继续执行,而不是崩溃。

2. 捕获异常

2.1 捕获常规异常

使用tryexcept语句可以捕获异常。try块包裹可能出错的代码,except块用于处理异常。

示例:

try:
f = open('linux.txt', 'r')
except:
f = open('linux.txt', 'w')

2.2 捕获指定异常

可以通过指定异常类型来捕获特定的错误。

示例:

try:
print(name)
except NameError as e:
print('name变量名称未定义错误')

注意事项:

  • 异常类型必须与except中的异常类型一致。
  • try内通常只放一行可能出错的代码。

2.3 捕获多个异常

可以将多个异常类型列出,使用元组表示。

示例:

try:
print(1/0)
except (NameError, ZeroDivisionError) as e:
print(e)

结果示意图:

Traceback (most recent call last):
File "
", line 2, in
ZeroDivisionError: division by zero

2.4 捕获所有异常

可以使用Exception作为通用异常捕获所有异常。

示例:

try:
print(name)
except Exception as e:
print(e)

2.5 使用else和finally

  • else块用于在try块未发生异常时执行。
  • finally块用于在tryexcept块完成后执行,总是会执行。

示例:

try:
f = open('test.txt', 'r')
except Exception as e:
f = open('test.txt', 'w')
else:
print('没有异常,真开心')
finally:
f.close()

3. 抛出异常

可以使用raise语句手动抛出异常。

示例:

def divide(x, y):
if y == 0:
raise ValueError("y cannot be zero")
return x / y
divide(4, 2)
divide(3, 0)

结果示意图:

Traceback (most recent call last):
File "
", line 6, in divide
File "
", line 2, in divide
ValueError: y cannot be zero

4. 自定义异常

有时标准异常不足以描述特定错误,可以自定义异常类。

示例:

class CustomError(Exception):
"""自定义异常类"""
def __init__(self, message):
self.message = message
def __str__(self):
return f"CustomError: {self.message}"
try:
raise CustomError("This is a custom error")
except CustomError as ce:
print(ce)

结果示意图:

CustomError: This is a custom error

5. 异常传递

在函数中未处理的异常会向上传递,直到被捕获或程序终止。

示例:

class CustomError(Exception):
"""自定义异常类"""
def __init__(self, message):
self.message = message
def __str__(self):
return f"CustomError: {self.message}"
def read_file(file_path):
try:
with open(file_path, 'r') as file:
return file.read()
except FileNotFoundError as e:
raise CustomError(f"File not found: {file_path}") from e
def process_file(file_path):
try:
content = read_file(file_path)
# 假设这里有其他处理文件内容的代码
return content
except CustomError as ce:
print(ce)
try:
file_content = process_file("non_existent_file.txt")
except CustomError as ce:
print(f"Handled at top level: {ce}")

转载地址:http://daofk.baihongyu.com/

你可能感兴趣的文章
python | xlwings,一个非常实用的 Excel 相关的 Python 库!
查看>>
python | xmltodict,一个非常厉害的 关于XML数据 Python 库!
查看>>
python | xonsh,一个超酷的 Python 库!
查看>>
python | yagmail,一个实用的 Python 库!
查看>>
python | 一文掌握Python的上下文管理器和with语句
查看>>
python | 一文看懂Python闭包机制与变量作用域规则
查看>>
python读取含中文的json
查看>>
python | 如何用Python锁避免并发错误?
查看>>
python | 提升代码迭代速度的Python重载方法
查看>>
python | 深入理解Python并发编程中的GIL限制与解决方案
查看>>
Python | 爬虫实战——亚马逊搜索页监控(附详细源码)
查看>>
python | 高效使用Python工具自动生成模块文档的秘诀
查看>>
python 一个list去除另一个list中的值
查看>>
python 三大框架的 介绍。
查看>>
Python 下载的 11 种姿势,一种比一种高级!
查看>>
python读取一个文件夹下所有图片_初学Python-找出文件夹下的所有图片
查看>>
Python 中 3 个不可思议的返回功能
查看>>
python 中 dict 的另一种用法
查看>>
Python 中 PIL 读取图片出现异常旋转的解决方法
查看>>
python读取word表格内容(1)
查看>>