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

引言

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

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函数,自定义记录异常信息。

 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!");
        }
    }

相关推荐

  1. C#返回多个方法

    2023-12-08 21:04:01       30 阅读
  2. C++返回返回引用、返回地址

    2023-12-08 21:04:01       59 阅读
  3. C++中vector返回最高效返回

    2023-12-08 21:04:01       58 阅读
  4. C++】表达式返回数据类型

    2023-12-08 21:04:01       53 阅读
  5. C++ 中返回优化

    2023-12-08 21:04:01       23 阅读
  6. Spring MVC controller方法返回

    2023-12-08 21:04:01       56 阅读
  7. SpringMvc处理器方法返回

    2023-12-08 21:04:01       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-08 21:04:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-08 21:04:01       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-08 21:04:01       82 阅读
  4. Python语言-面向对象

    2023-12-08 21:04:01       91 阅读

热门阅读

  1. Nump数组的拼接详细教程

    2023-12-08 21:04:01       52 阅读
  2. mysql获取时间异常

    2023-12-08 21:04:01       67 阅读
  3. TypeScript中泛型对象、泛型类

    2023-12-08 21:04:01       56 阅读
  4. 【python】vscode中选择虚拟环境venv

    2023-12-08 21:04:01       59 阅读
  5. Linux DAC权限的简单应用

    2023-12-08 21:04:01       53 阅读
  6. 做题笔记:SQL Sever 方式做牛客SQL的题目--VQ34

    2023-12-08 21:04:01       55 阅读
  7. 面试经典150题(1-2)

    2023-12-08 21:04:01       59 阅读