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