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!");
        }
    }
相关推荐
溪语流沙13 分钟前
【Python项目实战】部署上线:把博客发布到云服务器
服务器·开发语言·python
岁岁种桃花儿20 分钟前
Vue组件第六篇:Vue单文件组件
开发语言·前端·javascript·vue.js
朽棘不雕28 分钟前
Qt项目代码解释
开发语言·qt
计算机毕设定制辅导-无忧学长36 分钟前
《基于Java的旧物回收管理系统设计与实现》
java·开发语言
“AI国潮设计-小江”37 分钟前
【Python/SDXL实战】潮汕国潮IP视觉落地:普宁美食猫IP & 创意甜品设计(附ComfyUI工作流与商用授权思路)
开发语言·人工智能·python·prompt·aigc
sdm0704271 小时前
仿muduo库实现高并发服务器-下
开发语言·网络·c++·多路转接
爱奥尼欧1 小时前
【Git】远程分支删了本地还在、两个分支历史不相干?两招故障排解
开发语言·git
Java后端的Ai之路1 小时前
Git冲突完整排查与实战:本地修改覆盖报错到成功推送全流程复盘
开发语言·人工智能·git·python·pop
skywalk81631 小时前
AI 中台记录:使用码道基于deepseek harness制作AI数字中台9.14日
开发语言·人工智能·ai中台
CVer儿1 小时前
vs2022配置qt
开发语言·qt