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!");
        }
    }
相关推荐
总要学点什么3 分钟前
第104篇:三维特效-流动墙体效果——让贴图沿墙流动,它却只肯走一条对角线
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
旖旎夜光25 分钟前
【C++ 基础入门】C++11 新特性(中):右值引用、移动语义与完美转发
开发语言·c++·笔记·学习
ShineWinsu1 小时前
对于Qt:QTabWidget常见属性的解析
开发语言·数据库·c++·qt·浏览器·qtabwidget·标签页
普通人61 小时前
WebGL与WebGPU入门指南
开发语言·webgl·1024程序员节
꧁细听勿语情꧂2 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
SomeOtherTime2 小时前
Rust集合(AI回答)
开发语言·后端·rust
曦樂~2 小时前
【Web Development】03JavaScript 基础和事件
开发语言·前端·javascript
郝学胜-神的一滴2 小时前
LangChain Skill 实现(渐进披露 On-Demand Skill,LangChain 官方 Deep Agent Skill 模式)
开发语言·python·langchain·numpy
程序员Query3 小时前
day01-认识Go语言 + golang环境的安装
开发语言·后端·golang
§ꦿCFོ༉12 小时前
嵌入式八股文—C语言入门学习(四)
c语言·开发语言·学习