【问题标题】:Best practices for exiting a void method within a loop or submethod?在循环或子方法中退出 void 方法的最佳实践?
【发布时间】:2020-03-10 12:43:36
【问题描述】:

我正在尝试找出立即从其中的另一个子方法中退出方法的最佳方法。我知道我可以抛出异常,但我已经在该方法中有一个 try catch,它将捕获我抛出的任何异常。我基本上是在尝试做两次,比如 ping 服务器,如果第一次失败,捕获异常并重试,但如果第二次失败,退出整个方法。有我可以实现的 Initialize().Exit() 吗?从异常中抛出异常似乎不是最好的方法。如果初始 ping 失败或出现错误,我想捕捉,因为有时 ping 会失败,如果它执行其中任何一个,我会尝试连接到另一台服务器(未显示)。

public main()
{
    bool pingedOnce = false;
    try {
    Initialize();
    }
    catch (Exception e)
    {
        Console.WriteLine("e");
    }
}

public void Initialize()
{        
        try
        {

            if (new Ping().Send(server).Status == IPStatus.Success) //pings server to see if it exists
            {
                Console.WriteLine("Successfully Pinged " + server);
            }
            else
                throw new System.Exception();
        }
        catch (Exception e)
        {
            if (!pingedOnce)) //see if server has been pinged before
            {
                pingedOnce = True;
                Console.WriteLine("WARNING: failed to get data from server attempting to reconnect...");
                ReconnectToServer(server);
            }
            else
                throw new System.Exception("ERROR: Failed to connect to server after re-attempt.");
        }
}

类似问题的另一个例子:

public Main()
{
    Initialize();
}
public void Initialize()
{
    foreach(string s in serverIPList)
    {
        for (int i=0; i<5; i++;)
        {
            if (new Ping().Send(serverIPList[i]).Status == IPStatus.Success) //when it finds a server that it successfully pings, it exits the method
                Initialize().Exit(); //I want this to exit this for loop, the foreach loop, and the initialize method entirely.
        }
    }
}

理论上我可以不选择做一个 void 方法,只让它返回 null 并且从不将该方法分配给任何东西,但这比嵌套的 try catch 更好吗?

【问题讨论】:

  • 为什么不在方法中return
  • @Frontear - 听起来他们想从调用当前方法的方法返回。使用简单的return 是不可能的。
  • 如果你能判断它是否成功,你不应该使用 try/catch 来处理你的第二个 ping。只需检查状态,然后重试或继续。然后你可以从初始化方法返回一个真/假(或者你想要的任何东西,真的),以便被调用者可以决定下一步做什么。
  • 将 Initialize 返回类型从 void 更改为 bool 并在 main 方法中采取相应措施。
  • @Frontear 我会说“从另一个子方法中退出一个方法”似乎表明了这一点。虽然听起来确实很奇怪,但我不确定这就是 OP 的真正含义......

标签: c# exception methods ping exit-code


【解决方案1】:

如果你有异常抛出。否则返回!

if (new Ping().Send(server).Status == IPStatus.Success) //pings server to see if it exists
            {
                Console.WriteLine("Successfully Pinged " + server);
return; //RETURN here if you dont want to do anything!
            }
            else
                throw new System.Exception();

并在任何地方做同样的事情。因此,如果发生异常或方法将在您想要的地方停止,您可以捕获异常。

【讨论】:

  • OP 想要一个解决方案其他而不是例外。
  • 不@Frontear,这不准确,OP 只是不知道如何在异常情况下正确完成它。
  • 我同意 OP 并没有要求非异常解决方案,但我确实认为目前处理它的方式不是很好(他们本质上是使用第一个 try/catch 来驱动第二次尝试的逻辑)。如果重试失败,我看不出有任何压倒性的问题。
【解决方案2】:

如果您想坚持您的异常处理设计,建议您创建一个派生自 System.Exception 的自定义类。你几乎不应该抛出System.Exception;而是抛出一个更专业的异常,这使您能够以不同的方式捕获和处理每种类型的异常。例如:

    try
    {
        // this can throw different kinds of exceptions.
    }
    catch (InvalidOperationException e)
    {
        // do something.
    }
    catch (ArgumentException e)
    {
        // do something different.
    }

【讨论】:

  • 是的。第一条准则here 是不要抛出 System.Exception。
猜你喜欢
  • 2020-01-25
  • 1970-01-01
  • 2015-04-06
  • 2011-12-16
  • 1970-01-01
  • 2012-10-09
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多