C#使用异常中断方式,简化频繁判断返回值的流水式返回判断

引言

大家可能遇到这种情况,每一步函数调用都要判断返回结果是否正常顺序执行下一步。如下举例

csharp 复制代码
public static bool step1()  
{  
    return true;  
}  
  
public static bool step2()  
{  
    return true;  
}  
  
public static bool step3()  
{  
    return false;  
}  
  
public static bool step4()  
{  
    return true;  
}  
  
public static void Main()  
{  
    if (!step1())  
    {  
        Console.WriteLine("step1 fail!");  
        return;  
    }  
      
    if (!step2())  
    {  
        Console.WriteLine("step2 fail!");  
        return;  
    }  
      
    if (!step3())  
    {  
        Console.WriteLine("step3 fail!");  
        return;  
    }  
      
    if (!step4())  
    {  
        Console.WriteLine("step4 fail!");  
        return;  
    }  
      
    Console.WriteLine("All step ok!");  
}

这样调用频繁判断不够简洁美观并麻烦。

可以使用抛异常方式中断当前main函数,自定义记录异常信息。

csharp 复制代码
 public static bool step3()
    {
        throw new MyException("step3步骤执行失败");
        return false;
    }

    public static bool step4()
    {
        return true;
    }
    class MyException : Exception
    {
        public MyException(string message) : base(message)
        {
        }
    }
    public static void Main()
    {
        try
        {
            step1();
            step2();
            step3();
            step4();
            Console.WriteLine("All steps ok!");
        }
        catch (MyException ee)
        {
            Console.WriteLine(ee?.ToString()?? "step failed!");
        }
    }
相关推荐
qydz115 分钟前
杰理开发板做TWS耳机类型方案分享(1)
开发语言·pcb工艺·嵌入式开发·杰理科技
Cloud_Shy61835 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第六章 Item 40 - 43)
android·开发语言·人工智能·笔记·python·学习方法
半只小闲鱼41 分钟前
配置计划模块通用办公设备家具批复数合计计算
开发语言·python
qq_422152571 小时前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word
charliedev1 小时前
Jedi:Python 自动补全与静态分析的实用工具
开发语言·python·其他
ji198594431 小时前
MATLAB 求散点曲线斜率
开发语言·算法·matlab
kaikaile19951 小时前
MATLAB 实现:Koch & Zhao 图像水印算法(DCT域)
开发语言·算法·matlab
love_muming1 小时前
链表每日一练
java·开发语言·数据结构·链表·idea·每日一练
weixin_446260851 小时前
LLM智能体在社交模拟中的决策行为分析:有限状态与LLM-based策略对比研究
开发语言·php
牛肉在哪里2 小时前
ros2 从零开始28 监听广播C++
开发语言·c++·算法·机器人