def robust_calculator(): """一个健壮的计算器函数""" def safe_calculate(operation, a, b): """ 安全的计算函数 Args: operation: 操作类型 ('add', 'sub', 'mul', 'div') a, b: 操作数 Returns: 计算结果或错误信息 """ if operation not in ['add', 'sub', 'mul', 'div']: raise ValueError(f"不支持的操作: {operation}") if not all(isinstance(x, (int, float)) for x in [a, b]): raise TypeError("操作数必须是数字") try: if operation == 'add': result = a + b elif operation == 'sub': result = a - b elif operation == 'mul': result = a * b elif operation == 'div': if b == 0: raise ZeroDivisionError("除数不能为零") result = a / b assert isinstance(result, (int, float)), "计算结果应该是数字" except ZeroDivisionError as e: return f"错误: {e}" except Exception as e: print(f"[ERROR] 计算失败: {e}") raise else: if isinstance(result, float): result = round(result, 10) finally: print(f"[INFO] 计算 {operation}({a}, {b}) 完成") return result test_cases = [ ('add', 10, 5), ('div', 10, 2), ('div', 10, 0), ('mul', 3.14, 2), ('unknown', 1, 2), ('add', '10', 5), ] for op, a, b in test_cases: try: result = safe_calculate(op, a, b) print(f"{op}({a}, {b}) = {result}") except (ValueError, TypeError) as e: print(f"{op}({a}, {b}) 失败: {e}") print("-" * 40)
robust_calculator()
|