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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值