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!");
        }
    }
相关推荐
KookeeyLena88 分钟前
如何限制任何爬虫爬取网站的图片
开发语言·c++·爬虫
yanyanwenmeng27 分钟前
matlab基础
开发语言·算法·matlab
末央&44 分钟前
【C++】内存管理
java·开发语言·c++
不是仙人的闲人1 小时前
Qt日志输出及QsLog日志库
开发语言·数据库·qt
八了个戒1 小时前
【TypeScript入坑】TypeScript 的复杂类型「Interface 接口、class类、Enum枚举、Generics泛型、类型断言」
开发语言·前端·javascript·面试·typescript
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机轨迹跟踪及避障Matlab代码
开发语言·matlab·无人机
Yan-英杰1 小时前
Encountered error while trying to install package.> lxml
开发语言·python·pandas·pip·issue
卡卡_R-Python1 小时前
海洋气象编程工具-Python
开发语言·python
爱学习的真真子1 小时前
菜鸟也能轻松上手的Java环境配置方法
java·开发语言
豆本-豆豆奶1 小时前
23个Python在自然语言处理中的应用实例
开发语言·python·自然语言处理·编程语音