博客
关于我
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 操作 JMeter 探索:pymeter 实操指南
查看>>
Python 操作 Redis
查看>>
Python 操作Mysql(PyMysql)
查看>>
Python 操作Redis
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(一)
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(二)
查看>>
Python 操作数据库
查看>>
Python 数据分析与可视化实战
查看>>
python 数据可视化 -- matplotlib02
查看>>
python 数据可视化利器
查看>>
Python 数据可视化详解
查看>>
python 数据库查询返回list或tuple
查看>>
Python 数据库连接池管理的基本知识 (附Demo)
查看>>
Python学习记录-2016-12-17
查看>>
Python 数据库骚操作 -- MySQL
查看>>
Python 数据操作详解
查看>>
Python 数据文件与网络数据序列化存储详解
查看>>
Python 数据结构与算法详解
查看>>
Python 数据采集、清洗、整理、分析以及可视化实战
查看>>
Python 数据预处理
查看>>