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

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

Python异常处理详解

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

1. 错误类型

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

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

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

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

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

2. 捕获异常

2.1 捕获常规异常

使用try和except语句可以捕获异常。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块用于在try或except块完成后执行,总是会执行。

示例:

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关于 *args 和 **kwargs 参数的详解(全)
查看>>
Pythonfrozenset散列算法/实现
查看>>
PythonGTK+3:通过单击列对树视图进行排序
查看>>
pythonnumpy生成二进制流_python/numpy生成的二进制文件,由C读取
查看>>
pythonsign函数_对python函数签名的方法详解 用python怎么写一个自签名证书
查看>>
PythonStudy
查看>>
Pythons__IMPORT__未按预期工作
查看>>
Pythont通过request以及BeautifulSoup爬取几千条情话
查看>>
pythonweb django的学习
查看>>
pythonweb网站开发基础django安装
查看>>
pythonweb网站开发基础创建django项目
查看>>
pythonweb网站开发基础添加应用
查看>>
Python_015 多线程
查看>>
python_73_pickle序列化(接72)
查看>>
python_code_418
查看>>
python_day10 协程 GEVENT
查看>>
python_day1作业
查看>>
Python接口自动化测试必备基础之http协议详解!
查看>>
python_IDE开发环境使用_建立Python源文件---python工作笔记011
查看>>
Python_web框架解析
查看>>