You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python异常场景下变量赋值的优雅实现及通用处理方法

一行异常处理写法与通用方案

能不能写成一行代码?

当然可以,直接把try-except逻辑压缩到一行:

try: info['platform'] = platform.system() except Exception: info['platform'] = "NA"

不过这种写法可读性稍差,更优雅的方式是封装一个简短的辅助函数,再一行调用:

def get_with_default(func, default):
    try: return func()
    except Exception: return default

info['platform'] = get_with_default(platform.system, "NA")

这里直接传入platform.system函数对象,避免提前执行触发异常。

通用异常处理方法

  • 精准捕获特定异常:别用裸except,明确指定可能触发的异常类型(比如IO操作抓OSError、网络请求抓对应库的异常类),防止意外掩盖其他未知错误:
    try:
        info['platform'] = platform.system()
    except OSError:  # 示例,根据实际可能的异常调整
        info['platform'] = "NA"
    
  • 封装复用工具函数:如果多处需要“调用函数+异常返回默认值”的逻辑,写一个可扩展的通用函数:
    def get_with_default(func, default, exceptions=(Exception,)):
        try:
            return func()
        except exceptions:
            return default
    
    调用时可以指定要捕获的异常类型,灵活性更高。
  • 结合上下文管理器处理:如果需要忽略特定异常并确保默认值存在,可以用contextlib.suppress配合setdefault:
    from contextlib import suppress
    
    with suppress(OSError):
        info['platform'] = platform.system()
    info.setdefault('platform', "NA")
    
  • 提前预判规避异常:如果能提前判断异常触发的条件,先做检查再执行,比如确认属性/方法存在:
    info['platform'] = platform.system() if hasattr(platform, 'system') else "NA"
    
    这种方式只适用于可预判的场景,无法覆盖运行时突发异常。

内容的提问来源于stack exchange,提问作者Alexey Mirano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:19:47