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!");
        }
    }
相关推荐
百锦再7 分钟前
第8章 模块系统
android·java·开发语言·python·ai·rust·go
m0_5913389114 分钟前
day8鹏哥C语言--函数
c语言·开发语言·算法
oplp19 分钟前
回过头来重新对C语言进行深度学习(一)
c语言·开发语言
oioihoii32 分钟前
C++中的多态:动态多态与静态多态详解
java·开发语言·c++
毕设源码-朱学姐43 分钟前
【开题答辩全过程】以 基于Java的医务室病历管理小程序为例,包含答辩的问题和答案
java·开发语言·小程序
APIshop1 小时前
代码实战:PHP爬虫抓取信息及反爬虫API接口
开发语言·爬虫·php
kyle~1 小时前
C++---关键字constexpr
java·开发语言·c++
mudtools1 小时前
解放双手!使用Roslyn生成代码让你的 HTTP 客户端开发变得如此简单
低代码·c#·.net
weixin_438694392 小时前
pnpm 安装依赖后 仍然启动报的问题
开发语言·前端·javascript·经验分享
阿凡达蘑菇灯2 小时前
langgraph---条件边
开发语言·前端·javascript