当前位置:首页>python>Python错误与异常处理实战:让你的代码从“脆弱”到“坚不可摧”

Python错误与异常处理实战:让你的代码从“脆弱”到“坚不可摧”

  • 2026-03-24 14:40:36
Python错误与异常处理实战:让你的代码从“脆弱”到“坚不可摧”

嘿,学习搭子!咱们一起闯过了面向对象编程的高级关卡,是不是感觉自己写代码的水平又上了一个台阶?但你想过没有,如果程序运行中突然出错——文件打不开、网络断了、数据格式不对——你的代码会怎样?是直接崩溃,还是优雅地处理问题?今天咱们就来学习 “防御性编程” 的核心技能:错误与异常处理。别慌,我会像之前一样,带你一步步拆解,让你的代码从“脆弱”变得“坚不可摧”!

引言:为什么需要错误与异常处理?

你有没有遇到过这样的尴尬时刻:

  • • 辛辛苦苦写了个数据处理脚本,运行到一半因为文件不存在直接崩溃,前面的功夫全白费?
  • • 用户输入了一个不合法的数据,程序直接报错退出,留下用户一脸懵?
  • • 网络请求失败时,程序直接“罢工”,没有任何提示和恢复机会?

如果你的答案是“是的,我正为这事儿头疼呢!”,那今天这篇文章就是为你量身定做的。咱们要系统学习 异常体系、异常捕获与处理、自定义异常、异常链、上下文管理器、异常日志记录 等核心技能。通过设计 健壮的文件处理、网络请求重试、数据验证包装 等实际案例,你将掌握如何让程序在面对错误时依然能“从容应对”。

学习目标:学完本章,你不仅能理解Python异常处理机制,还能设计出健壮、可维护的错误处理策略。预期成果:掌握异常处理的核心模式,能编写出即使遇到意外也能优雅处理的代码,并为后续学习文件操作与数据持久化打下坚实基础。

核心内容:错误与异常处理深度解析

1. Python异常体系:错误也有“家谱”

在Python中,异常不是“妖魔鬼怪”,而是一种特殊的对象。它们按照继承关系形成了一个清晰的“家谱”。了解这个体系,你就能知道该捕获什么、该抛出什么。

BaseException家族树

BaseException(所有异常的基类)├── SystemExit(程序退出)├── KeyboardInterrupt(键盘中断)├── GeneratorExit(生成器退出)└── Exception(所有内置异常的基类)    ├── ArithmeticError(算术错误)    │   ├── ZeroDivisionError(除零错误)    │   └── OverflowError(数值溢出)    ├── LookupError(查找错误)    │   ├── IndexError(索引错误)    │   └── KeyError(键错误)    ├── OSError(操作系统错误)    │   ├── FileNotFoundError(文件不存在)    │   └── PermissionError(权限不足)    ├── TypeError(类型错误)    ├── ValueError(值错误)    └── ...(还有很多)

关键点

  • • BaseException:所有异常的祖宗,一般不应该直接捕获它
  • • Exception:几乎所有内置异常的父类,你应该捕获的是这个或它的子类
  • • 特定异常:如FileNotFoundErrorZeroDivisionError等,捕获特定异常能让代码更清晰

为什么不要捕获BaseException

try:# 一些代码    user_input = input("请输入: ")    result = 10 / int(user_input)except BaseException:  # 危险!连KeyboardInterrupt也会被捕获print("出错了")# 用户按Ctrl+C想退出程序,结果被捕获了,程序退不出!

正确的做法是:

try:    user_input = input("请输入: ")    result = 10 / int(user_input)except ValueError:  # 输入的不是数字print("请输入有效的数字")except ZeroDivisionError:  # 除零错误print("除数不能为零")except Exception as e:  # 其他所有异常print(f"发生了未知错误: {e}")

2. 异常捕获与处理:try-except-else-finally四件套

Python提供了完整的异常处理结构,咱们一个个来看:

try-except:基础捕获

try:# 可能出错的代码    file = open("data.txt""r")    content = file.read()    file.close()except FileNotFoundError:# 文件不存在时的处理print("文件不存在,将创建新文件")    content = ""

多个except子句

try:    num = int(input("请输入一个数字: "))    result = 100 / numexcept ValueError:print("输入的不是有效的数字")except ZeroDivisionError:print("除数不能为零")except (TypeError, OverflowError):  # 同时捕获多种异常print("类型错误或数值溢出")

else:没有异常时执行

else子句在没有发生异常时执行,让你的代码逻辑更清晰:

try:    result = perform_calculation(data)except CalculationError:print("计算失败")else:# 只有在没有异常时才执行print(f"计算结果: {result}")    save_result(result)# 对比:如果不使用else,代码会这样写try:    result = perform_calculation(data)# 如果上面有异常,这两行不会执行print(f"计算结果: {result}")    save_result(result)except CalculationError:print("计算失败")

哪种更清晰?明显第一种!else让“正常流程”和“异常处理”分离。

finally:无论如何都要执行

finally子句无论是否发生异常都会执行,常用于清理资源:

file = Nonetry:    file = open("data.txt""r")    content = file.read()    process(content)except FileNotFoundError:print("文件不存在")finally:# 无论是否发生异常,都要关闭文件if file:        file.close()print("资源清理完成")

经典应用场景

  • • 关闭文件
  • • 关闭数据库连接
  • • 释放锁
  • • 清理临时文件

完整示例:四件套协同工作

defprocess_file(filename):"""处理文件,演示完整的异常处理结构"""    file = Nonetry:print(f"正在打开文件: {filename}")        file = open(filename, "r", encoding="utf-8")        content = file.read()except FileNotFoundError:print(f"错误: 文件 {filename} 不存在")returnNoneexcept PermissionError:print(f"错误: 没有权限读取文件 {filename}")returnNoneexcept UnicodeDecodeError:print(f"错误: 文件 {filename} 编码不是UTF-8")returnNoneelse:print("文件读取成功")# 这里可以处理content        processed = content.upper()return processedfinally:if file:            file.close()print("文件已关闭")print("处理流程结束")

3. 自定义异常:让你的错误信息更清晰

内置异常虽然丰富,但有时我们需要表达业务逻辑错误。这时候就该自定义异常登场了。

为什么要自定义异常?

  1. 1. 语义更清晰InsufficientFundsErrorValueError更能表达"余额不足"
  2. 2. 分层处理:可以针对不同业务异常采取不同处理策略
  3. 3. 携带更多信息:自定义异常可以携带业务相关的上下文信息

如何创建自定义异常?

# 基础版:简单继承ExceptionclassValidationError(Exception):"""数据验证错误"""pass# 增强版:携带额外信息classInsufficientFundsError(Exception):"""余额不足异常"""def__init__(self, balance, amount):self.balance = balanceself.amount = amountself.shortfall = amount - balancesuper().__init__(f"余额不足: 当前余额{balance},需要{amount},缺少{self.shortfall}")# 使用defwithdraw(balance, amount):if amount > balance:raise InsufficientFundsError(balance, amount)return balance - amounttry:    withdraw(100200)except InsufficientFundsError as e:print(f"取款失败: {e}")print(f"缺少金额: {e.shortfall}")

实战:电商系统的自定义异常

classShoppingCartError(Exception):"""购物车错误基类"""passclassItemNotFoundError(ShoppingCartError):"""商品未找到"""def__init__(self, item_id):self.item_id = item_idsuper().__init__(f"商品ID {item_id} 不存在")classOutOfStockError(ShoppingCartError):"""商品缺货"""def__init__(self, item_id, stock):self.item_id = item_idself.stock = stocksuper().__init__(f"商品ID {item_id} 缺货,当前库存: {stock}")classCartLimitExceededError(ShoppingCartError):"""购物车数量限制"""def__init__(self, item_id, quantity, limit):self.item_id = item_idself.quantity = quantityself.limit = limitsuper().__init__(f"商品ID {item_id} 数量{quantity}超过限制{limit}")# 使用示例defadd_to_cart(cart, item_id, quantity):# 模拟检查ifnot item_exists(item_id):raise ItemNotFoundError(item_id)if get_stock(item_id) < quantity:raise OutOfStockError(item_id, get_stock(item_id))if quantity > 10:  # 假设限制10个raise CartLimitExceededError(item_id, quantity, 10)# 正常逻辑    cart.add(item_id, quantity)

4. 异常链(raise from):保留完整的错误上下文

有时候,我们在处理一个异常时,需要抛出另一个异常。但原始异常的信息很重要,不能丢失。这时候就该raise from登场了。

问题:异常上下文丢失

defread_config():try:withopen("config.json""r"as f:return json.load(f)except FileNotFoundError:raise ValueError("配置文件不存在")  # 原始异常信息丢失!# 调用者只能看到ValueError,不知道根本原因是FileNotFoundError

解决方案:使用raise from

defread_config():try:withopen("config.json""r"as f:return json.load(f)except FileNotFoundError as e:raise ValueError("配置文件不存在"from e# 现在调用者能看到完整的异常链try:    config = read_config()except ValueError as e:print(f"错误: {e}")print(f"根本原因: {e.__cause__}")  # 输出: FileNotFoundError

更复杂的异常链示例

classDataProcessingError(Exception):"""数据处理错误"""passdefprocess_data_file(filename):try:# 尝试读取文件withopen(filename, "r"as f:            data = f.read()except OSError as e:# 包装为业务异常,保留原始异常raise DataProcessingError(f"无法读取文件 {filename}"from etry:# 尝试解析JSON        parsed = json.loads(data)except json.JSONDecodeError as e:# 包装为业务异常,保留原始异常raise DataProcessingError(f"文件 {filename} 不是有效的JSON"from etry:# 处理数据        result = complex_data_processing(parsed)return resultexcept Exception as e:# 包装为业务异常,保留原始异常raise DataProcessingError("数据处理失败"from e# 使用try:    result = process_data_file("data.json")except DataProcessingError as e:print(f"数据处理失败: {e}")# 可以追溯完整的异常链    cause = e.__cause__while cause:print(f"  -> {type(cause).__name__}{cause}")        cause = cause.__cause__

5. 上下文管理器(with语句)与异常处理

上下文管理器是Python中优雅处理资源的利器。它自动处理资源的获取和释放,即使发生异常也能确保清理。

内置上下文管理器示例

# 文件操作:自动关闭文件withopen("data.txt""r"as file:    content = file.read()# 即使这里发生异常,文件也会自动关闭    process(content)# 锁操作:自动释放锁import threadinglock = threading.Lock()with lock:# 临界区代码    shared_data.append(item)# 离开with块时自动释放锁

自定义上下文管理器

有两种方式创建上下文管理器:类方式和装饰器方式。

类方式

classDatabaseConnection:"""数据库连接上下文管理器"""def__init__(self, connection_string):self.connection_string = connection_stringself.connection = Nonedef__enter__(self):print("建立数据库连接...")self.connection = create_connection(self.connection_string)returnself.connectiondef__exit__(self, exc_type, exc_val, exc_tb):print("关闭数据库连接...")ifself.connection:self.connection.close()# 如果发生异常,可以选择处理或不处理if exc_type:print(f"发生异常: {exc_type.__name__}{exc_val}")# 返回True表示异常已处理,不会向上传播# 返回False表示异常未处理,会继续向上传播returnFalse# 让异常继续传播returnTrue# 正常结束# 使用with DatabaseConnection("mysql://user:pass@localhost/db"as db:    result = db.query("SELECT * FROM users")    process(result)# 即使这里发生异常,连接也会自动关闭

装饰器方式(更简单)

from contextlib import contextmanager@contextmanagerdeftemporary_file(content):"""创建临时文件的上下文管理器"""import tempfileimport ostry:# __enter__部分        temp_file = tempfile.NamedTemporaryFile(mode="w", delete=False)        temp_file.write(content)        temp_file.close()print(f"创建临时文件: {temp_file.name}")yield temp_file.name  # 给with块使用的值finally:# __exit__部分print(f"删除临时文件: {temp_file.name}")        os.unlink(temp_file.name)# 使用with temporary_file("Hello, World!"as filename:withopen(filename, "r"as f:print(f.read())# 离开with块时自动删除临时文件

上下文管理器在异常处理中的优势

# 传统方式file = Nonetry:    file = open("data.txt""r")# 处理文件    process(file)except Exception as e:print(f"错误: {e}")finally:if file:        file.close()# 使用上下文管理器(更简洁!)try:withopen("data.txt""r"as file:        process(file)except Exception as e:print(f"错误: {e}")

6. 异常日志记录:不仅仅是打印错误

当程序在生产环境运行时,不能只是简单地打印错误信息。我们需要记录日志,以便后续分析和调试。

基础日志记录

import logging# 配置日志logging.basicConfig(    level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',    handlers=[        logging.FileHandler('app.log'),  # 输出到文件        logging.StreamHandler()          # 输出到控制台    ])logger = logging.getLogger(__name__)defprocess_data(data):try:        result = complex_operation(data)        logger.info(f"数据处理成功: {result}")return resultexcept ValueError as e:        logger.error(f"数据值错误: {e}", exc_info=True)returnNoneexcept Exception as e:        logger.critical(f"未知错误: {e}", exc_info=True)raise

结构化日志记录(更高级)

import loggingimport jsonclassStructuredLogger:"""结构化日志记录器"""def__init__(self, name):self.logger = logging.getLogger(name)deflog_error(self, error_type, message, context=None, exc_info=False):"""记录结构化错误日志"""        log_data = {"timestamp": datetime.now().isoformat(),"level""ERROR","error_type": error_type,"message": message,"context": context or {},"exception_info"self._get_exception_info() if exc_info elseNone        }self.logger.error(json.dumps(log_data, ensure_ascii=False, default=str))def_get_exception_info(self):"""获取异常信息"""import tracebackimport sys        exc_type, exc_value, exc_tb = sys.exc_info()return {"type": exc_type.__name__ if exc_type elseNone,"message"str(exc_value) if exc_value elseNone,"traceback": traceback.format_tb(exc_tb) if exc_tb elseNone        }# 使用logger = StructuredLogger("data_processor")try:    result = risky_operation()except FileNotFoundError as e:    logger.log_error("FileNotFound","配置文件不存在",        context={"filename""config.json""user""alice"},        exc_info=True    )raise

日志级别与使用场景

级别
数值
使用场景
CRITICAL
50
严重错误,程序可能无法继续运行
ERROR
40
错误,但程序还能运行
WARNING
30
警告,可能有问题但未出错
INFO
20
一般信息,记录程序运行状态
DEBUG
10
调试信息,记录详细过程
NOTSET
0
未设置

最佳实践

  • • 生产环境使用INFO级别
  • • 开发环境使用DEBUG级别
  • • 错误日志一定要包含足够的上下文信息
  • • 敏感信息(如密码)不要记录在日志中

示例代码:完整的错误处理案例

案例1:文件读取安全处理

import osimport loggingfrom pathlib import Pathlogger = logging.getLogger(__name__)classFileProcessor:"""安全的文件处理器"""def__init__(self, default_encoding='utf-8'):self.default_encoding = default_encodingdefread_file_safely(self, filepath, encodings=None):"""        安全读取文件,支持多种编码尝试        参数:            filepath: 文件路径            encodings: 尝试的编码列表,默认['utf-8', 'gbk', 'latin-1']        返回:            文件内容,如果失败返回None        """if encodings isNone:            encodings = ['utf-8''gbk''latin-1']        filepath = Path(filepath)# 检查文件是否存在ifnot filepath.exists():            logger.error(f"文件不存在: {filepath}")returnNone# 检查是否是文件ifnot filepath.is_file():            logger.error(f"路径不是文件: {filepath}")returnNone# 检查文件大小(避免读取过大文件)        file_size = filepath.stat().st_sizeif file_size > 100 * 1024 * 1024:  # 100MB限制            logger.error(f"文件过大: {filepath} ({file_size}字节)")returnNone# 尝试不同编码读取for encoding in encodings:try:withopen(filepath, 'r', encoding=encoding) as f:                    content = f.read()                    logger.info(f"成功读取文件: {filepath}, 编码: {encoding}")return contentexcept UnicodeDecodeError:                logger.debug(f"编码{encoding}失败,尝试下一个")continueexcept PermissionError:                logger.error(f"没有权限读取文件: {filepath}")returnNoneexcept Exception as e:                logger.error(f"读取文件时发生未知错误: {e}", exc_info=True)returnNone# 所有编码都失败        logger.error(f"无法用任何编码读取文件: {filepath}")returnNonedefprocess_data_file(self, filepath):"""处理数据文件,包含完整的异常处理"""try:            content = self.read_file_safely(filepath)if content isNone:raise FileProcessingError(f"无法读取文件: {filepath}")# 尝试解析为JSONtry:import json                data = json.loads(content)except json.JSONDecodeError as e:raise DataFormatError(f"文件不是有效的JSON: {filepath}"from e# 验证数据self._validate_data(data)# 处理数据            result = self._process_data(data)            logger.info(f"文件处理成功: {filepath}")return resultexcept (FileProcessingError, DataFormatError) as e:# 业务异常,记录日志但不重新抛出            logger.warning(f"业务处理失败: {e}")returnNoneexcept Exception as e:# 未知异常,记录日志并重新抛出            logger.critical(f"处理文件时发生未知错误: {e}", exc_info=True)raise# 自定义异常classFileProcessingError(Exception):passclassDataFormatError(Exception):pass

案例2:网络请求异常重试机制

import requestsimport timeimport loggingfrom functools import wrapslogger = logging.getLogger(__name__)classRetryableError(Exception):"""可重试的错误"""passclassFatalError(Exception):"""致命错误,不应重试"""passdefretry_on_failure(max_retries=3, delay=1, backoff=2):"""    重试装饰器    参数:        max_retries: 最大重试次数        delay: 初始延迟时间(秒)        backoff: 延迟倍数    """defdecorator(func):        @wraps(func)defwrapper(*args, **kwargs):            last_exception = Nonefor attempt inrange(max_retries + 1):  # +1表示第一次尝试try:return func(*args, **kwargs)except RetryableError as e:                    last_exception = eif attempt < max_retries:                        wait_time = delay * (backoff ** attempt)                        logger.warning(f"尝试 {func.__name__} 失败 (第{attempt + 1}次),"f"{wait_time}秒后重试。错误: {e}"                        )                        time.sleep(wait_time)else:                        logger.error(f"{func.__name__} 重试{max_retries}次后仍失败"                        )raiseexcept FatalError as e:                    logger.error(f"致命错误,不重试: {e}")raiseexcept Exception as e:# 未知异常,记录日志并重新抛出                    logger.error(f"未知错误: {e}", exc_info=True)raise# 所有重试都失败raise last_exceptionreturn wrapperreturn decoratorclassAPIClient:"""带重试机制的API客户端"""def__init__(self, base_url, timeout=10):self.base_url = base_urlself.timeout = timeoutself.session = requests.Session()    @retry_on_failure(max_retries=3, delay=1, backoff=2)defget_with_retry(self, endpoint, params=None):"""带重试的GET请求"""        url = f"{self.base_url}/{endpoint}"try:            response = self.session.get(                url,                 params=params,                 timeout=self.timeout            )            response.raise_for_status()  # 如果状态码不是2xx,抛出HTTPErrorreturn response.json()except requests.Timeout:            logger.warning(f"请求超时: {url}")raise RetryableError("请求超时")except requests.ConnectionError:            logger.warning(f"连接错误: {url}")raise RetryableError("连接错误")except requests.HTTPError as e:            status_code = e.response.status_code# 5xx错误可重试if500 <= status_code < 600:                logger.warning(f"服务器错误({status_code}): {url}")raise RetryableError(f"服务器错误: {status_code}")# 4xx错误不重试(客户端错误)else:                logger.error(f"客户端错误({status_code}): {url}")raise FatalError(f"客户端错误: {status_code}")except ValueError as e:# JSON解析错误            logger.error(f"响应不是有效的JSON: {url}")raise FatalError("响应格式错误")except Exception as e:            logger.error(f"未知错误: {e}", exc_info=True)raisedeffetch_user_data(self, user_id):"""获取用户数据,包含完整的错误处理"""try:            data = self.get_with_retry(f"users/{user_id}")# 验证响应数据ifnotisinstance(data, dictor'id'notin data:raise DataValidationError("响应数据格式无效")return dataexcept FatalError as e:# 致命错误,返回None或默认值            logger.error(f"获取用户数据失败: {e}")returnNoneexcept Exception as e:# 其他异常,记录日志并重新抛出            logger.critical(f"获取用户数据时发生未知错误: {e}", exc_info=True)raise# 使用示例if __name__ == "__main__":    logging.basicConfig(level=logging.INFO)    client = APIClient("https://api.example.com")try:        user_data = client.fetch_user_data(123)if user_data:print(f"用户数据: {user_data}")else:print("无法获取用户数据")except Exception as e:print(f"程序出错: {e}")

案例3:数据验证异常包装

import refrom datetime import datetimefrom typing importAnyDictListOptionalclassValidationError(Exception):"""验证错误基类"""def__init__(self, field: str, message: str, value: Any = None):self.field = fieldself.message = messageself.value = valuesuper().__init__(f"{field}{message}")classRequiredFieldError(ValidationError):"""必填字段错误"""passclassTypeValidationError(ValidationError):"""类型验证错误"""passclassRangeValidationError(ValidationError):"""范围验证错误"""passclassFormatValidationError(ValidationError):"""格式验证错误"""passclassDataValidator:"""数据验证器"""def__init__(self, data: Dict[strAny]):self.data = dataself.errors: List[ValidationError] = []defrequired(self, field: str) -> 'DataValidator':"""检查字段是否必填"""if field notinself.data orself.data[field] in (None"", [], {}):self.errors.append(                RequiredFieldError(field, "此字段为必填项")            )returnselfdeftype_check(self, field: str, expected_type: type) -> 'DataValidator':"""检查字段类型"""if field inself.data:            value = self.data[field]ifnotisinstance(value, expected_type):self.errors.append(                    TypeValidationError(                        field, f"必须是{expected_type.__name__}类型",                        value                    )                )returnselfdefrange_check(self, field: str, min_val=None, max_val=None) -> 'DataValidator':"""检查数值范围"""if field inself.data:            value = self.data[field]ifisinstance(value, (intfloat)):if min_val isnotNoneand value < min_val:self.errors.append(                        RangeValidationError(                            field,f"不能小于{min_val}",                            value                        )                    )if max_val isnotNoneand value > max_val:self.errors.append(                        RangeValidationError(                            field,f"不能大于{max_val}",                            value                        )                    )returnselfdefregex_check(self, field: str, pattern: str, message: str) -> 'DataValidator':"""正则表达式检查"""if field inself.data:            value = self.data[field]ifisinstance(value, str):ifnot re.match(pattern, value):self.errors.append(                        FormatValidationError(field, message, value)                    )returnselfdefcustom_check(self, field: str, check_func, message: str) -> 'DataValidator':"""自定义检查"""if field inself.data:            value = self.data[field]ifnot check_func(value):self.errors.append(                    ValidationError(field, message, value)                )returnselfdefvalidate(self) -> bool:"""执行验证,返回是否通过"""returnlen(self.errors) == 0defget_errors(self) -> List[ValidationError]:"""获取所有错误"""returnself.errorsdefraise_if_invalid(self):"""如果验证失败,抛出聚合异常"""ifself.errors:raise ValidationAggregateError(self.errors)classValidationAggregateError(Exception):"""聚合验证错误"""def__init__(self, errors: List[ValidationError]):self.errors = errors        error_messages = [str(e) for e in errors]super().__init__("; ".join(error_messages))def__str__(self):        error_lines = [f"{i+1}{str(e)}"for i, e inenumerate(self.errors)]return"验证失败:\n" + "\n".join(error_lines)# 使用示例:用户注册数据验证defvalidate_user_registration(data: Dict[strAny]) -> Dict[strAny]:"""验证用户注册数据"""    validator = DataValidator(data)    validator.required("username") \             .type_check("username"str) \             .range_check("username", min_len=3, max_len=20) \             .regex_check("username"r"^[a-zA-Z0-9_]+$""用户名只能包含字母、数字和下划线")    validator.required("email") \             .type_check("email"str) \             .regex_check("email"r"^[^@]+@[^@]+\.[^@]+$""邮箱格式不正确")    validator.required("password") \             .type_check("password"str) \             .range_check("password", min_len=8, max_len=100) \             .custom_check("password"lambda p: any(c.isupper() for c in p) andany(c.isdigit() for c in p),"密码必须包含至少一个大写字母和一个数字")    validator.required("age") \             .type_check("age"int) \             .range_check("age", min_val=18, max_val=120)# 检查确认密码if"password"in data and"confirm_password"in data:if data["password"] != data["confirm_password"]:            validator.errors.append(                ValidationError("confirm_password""两次输入的密码不一致")            )# 如果验证失败,抛出聚合异常    validator.raise_if_invalid()# 验证通过,返回清理后的数据return {"username": data["username"].strip(),"email": data["email"].strip().lower(),"password": data["password"],  # 实际中应该哈希"age": data["age"],"registered_at": datetime.now()    }# 使用try:    user_data = {"username""john_doe","email""john@example.com","password""Password123","confirm_password""Password123","age"25    }    validated = validate_user_registration(user_data)print("注册数据验证通过:", validated)except ValidationAggregateError as e:print("验证失败:")for error in e.errors:print(f"  - {error.field}{error.message}")except Exception as e:print(f"发生未知错误: {e}")

阶梯式练习

第一部分:选择题(10道,检测概念理解)

  1. 1. Python异常体系的基类是?A) ExceptionB) BaseExceptionC) ErrorD) Throwable
  2. 2. 哪个异常是文件不存在时抛出的?A) IOErrorB) FileErrorC) FileNotFoundErrorD) NotFoundError
  3. 3. try-except-else-finally中,else子句何时执行?A) 总是执行B) 发生异常时执行C) 没有发生异常时执行D) 无论是否异常都执行
  4. 4. finally子句的主要作用是?A) 处理异常B) 无论是否异常都执行清理C) 替代exceptD) 定义自定义异常
  5. 5. 创建自定义异常时,通常继承哪个类?A) BaseExceptionB) ExceptionC) objectD) Error
  6. 6. raise ValueError("错误") from original_error的作用是?A) 忽略原始错误B) 替换原始错误C) 保留原始错误上下文D) 创建新的错误类型
  7. 7. 上下文管理器的__exit__方法何时被调用?A) 进入with块时B) 离开with块时C) 发生异常时D) 手动调用时
  8. 8. 日志级别从低到高的正确顺序是?A) DEBUG, INFO, WARNING, ERROR, CRITICALB) INFO, DEBUG, WARNING, ERROR, CRITICALC) DEBUG, WARNING, INFO, ERROR, CRITICALD) INFO, WARNING, DEBUG, ERROR, CRITICAL
  9. 9. 哪个魔法方法让对象可以作为上下文管理器使用?A) __enter____exit__B) __start____end__C) __open____close__D) __init____del__
  10. 10. except (ValueError, TypeError) as e:这行代码的作用是?A) 捕获ValueError或TypeErrorB) 捕获所有异常C) 捕获ValueError和TypeError同时发生D) 语法错误

答案:1.B 2.C 3.C 4.B 5.B 6.C 7.B 8.A 9.A 10.A

第二部分:实战练习

任务要求:编写一个健壮的数据处理脚本,包含多层异常处理。脚本需要处理以下场景:

  1. 1. 文件读取与验证
    • • 从命令行参数接收文件路径
    • • 支持多种文件格式:JSON、CSV、TXT
    • • 自动检测文件格式并选择正确的解析器
    • • 文件不存在、权限不足、编码错误时给出友好提示
  2. 2. 数据清洗与转换
    • • 对数据进行清洗(去除空值、无效数据)
    • • 类型转换和格式标准化
    • • 数据验证(范围检查、格式检查)
  3. 3. 错误处理与恢复
    • • 实现多层异常处理:文件级、解析级、数据级
    • • 使用自定义异常区分不同错误类型
    • • 实现错误恢复机制(如跳过错误行继续处理)
    • • 详细的日志记录
  4. 4. 输出与报告
    • • 处理成功时输出清洗后的数据
    • • 处理失败时生成错误报告
    • • 统计处理结果(成功/失败记录数)

实现要求

  • • 至少使用3个自定义异常类
  • • 使用上下文管理器管理文件资源
  • • 实现异常链(raise from)保留错误上下文
  • • 使用日志记录不同级别的信息
  • • 代码结构清晰,有详细注释

示例数据结构(JSON格式):

[{"id":1,"name":"张三","age":25,"email":"zhangsan@example.com"},{"id":2,"name":"李四","age":"三十","email":"invalid-email"},{"id":3,"name":"王五","age":35,"email":"wangwu@example.com"}]

预期输出

  • • 成功处理有效数据
  • • 跳过或修复无效数据
  • • 生成处理报告

扩展挑战

  • • 添加数据去重功能
  • • 支持数据聚合统计
  • • 实现处理进度显示

总结预告

本章核心要点回顾

通过今天的实战,咱们一起掌握了Python错误与异常处理的核心技能:

  1. 1. 异常体系:理解了BaseException家族树,知道了该捕获什么、不该捕获什么
  2. 2. 异常捕获四件套:熟练运用try-except-else-finally进行结构化异常处理
  3. 3. 自定义异常:学会了创建业务异常,让错误信息更清晰、更有针对性
  4. 4. 异常链:掌握了raise from用法,保留了完整的错误上下文
  5. 5. 上下文管理器:使用with语句优雅管理资源,确保即使异常也能正确清理
  6. 6. 异常日志记录:学会了记录结构化日志,便于后续分析和调试

这些技能让你的代码从"脆弱"变得"坚不可摧"。记住:好的错误处理不是让程序永不出错,而是让程序在出错时依然能优雅地应对

下章预告:文件操作与数据持久化进阶

学完了错误与异常处理,下周咱们要进入 "数据存储与持久化" 的新篇章——文件操作与数据持久化进阶。

你将学到

  • • 高级文件操作技巧:二进制文件、大文件分块处理
  • • 多种数据持久化方案:JSON、CSV、Pickle、SQLite数据库
  • • 文件系统操作:目录遍历、文件监控、权限管理
  • • 数据备份与恢复策略
  • • 性能优化:缓存、压缩、并行处理

实战项目:咱们将开发一个完整的数据备份工具,支持多种存储格式、增量备份、错误恢复和进度报告。

学习搭子,错误处理是编程中的"安全气囊",平时可能用不到,但关键时刻能救命。多加练习,把这些模式内化成你的编程习惯。有任何问题,随时来找我讨论!

记住:优秀的程序员不是写出没有bug的代码,而是写出即使有bug也能优雅处理的代码。

"程序的第一要义是正确,第二要义是健壮,第三要义才是高效。" —— Python之禅

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-03-27 09:55:30 HTTP/2.0 GET : https://f.mffb.com.cn/a/479594.html
  2. 运行时间 : 0.103530s [ 吞吐率:9.66req/s ] 内存消耗:4,936.02kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=f9d06ca23124cd70e394d055ad00b266
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000625s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000712s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000358s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.000252s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000503s ]
  6. SELECT * FROM `set` [ RunTime:0.000214s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000548s ]
  8. SELECT * FROM `article` WHERE `id` = 479594 LIMIT 1 [ RunTime:0.001885s ]
  9. UPDATE `article` SET `lasttime` = 1774576530 WHERE `id` = 479594 [ RunTime:0.008856s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.000254s ]
  11. SELECT * FROM `article` WHERE `id` < 479594 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.000626s ]
  12. SELECT * FROM `article` WHERE `id` > 479594 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.000432s ]
  13. SELECT * FROM `article` WHERE `id` < 479594 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.000766s ]
  14. SELECT * FROM `article` WHERE `id` < 479594 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.000914s ]
  15. SELECT * FROM `article` WHERE `id` < 479594 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.004763s ]
0.105143s