MST

星途 面试题库

面试题:Python 自定义异常类在 try - except 块中的复杂应用

假设你正在开发一个金融交易系统,其中有一个交易类 `Transaction`。在交易过程中,如果交易金额超过账户余额,会引发 `InsufficientFundsError` 异常;如果交易类型不被支持,会引发 `UnsupportedTransactionTypeError` 异常。这两个异常均为自定义异常类,它们继承自一个基类 `TransactionError`。请编写代码实现这个交易类,并在一个函数中使用 try - except 块处理可能出现的异常,同时,当捕获到 `TransactionError` 及其子类异常时,记录异常信息到日志文件中,并且在日志中要体现异常发生的时间、交易相关的详细信息等,日志记录格式需符合标准的日志规范。
15.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import logging
from datetime import datetime


class TransactionError(Exception):
    pass


class InsufficientFundsError(TransactionError):
    pass


class UnsupportedTransactionTypeError(TransactionError):
    pass


class Transaction:
    def __init__(self, account_balance, transaction_type, amount):
        self.account_balance = account_balance
        self.transaction_type = transaction_type
        self.amount = amount

    def execute(self):
        if self.amount > self.account_balance:
            raise InsufficientFundsError
        supported_types = ['deposit', 'withdraw']
        if self.transaction_type not in supported_types:
            raise UnsupportedTransactionTypeError


def process_transaction(transaction):
    logging.basicConfig(filename='transaction.log', level=logging.ERROR,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    try:
        transaction.execute()
        print("交易成功")
    except TransactionError as e:
        error_info = f"交易类型: {transaction.transaction_type}, 交易金额: {transaction.amount}, 账户余额: {transaction.account_balance}"
        logging.error(f"{type(e).__name__}: {error_info}")


if __name__ == "__main__":
    # 示例使用
    t1 = Transaction(100, 'withdraw', 200)
    process_transaction(t1)
    t2 = Transaction(100, 'transfer', 50)
    process_transaction(t2)

代码说明:

  1. 异常类定义:定义了 TransactionError 作为基类,以及 InsufficientFundsErrorUnsupportedTransactionTypeError 两个子类,分别表示资金不足和不支持的交易类型异常。
  2. 交易类 Transaction:构造函数接受账户余额、交易类型和交易金额作为参数。execute 方法执行交易,如果交易金额超过账户余额或交易类型不被支持,会抛出相应的异常。
  3. 异常处理函数 process_transaction:使用 try - except 块捕获 TransactionError 及其子类异常。使用 logging 模块将异常信息记录到 transaction.log 文件中,日志格式符合标准规范,包含异常发生时间、异常级别和异常详细信息。
  4. 示例使用:创建了两个 Transaction 实例,并调用 process_transaction 函数进行处理,展示异常的触发和处理过程。