Search code examples
c#exceptionmethodspingexit-code

Best practices for exiting a void method within a loop or submethod?


I'm trying to figure out the best way to immediately exit a method from within another submethod inside of it. I know I can throw an exception BUT I already have a try catch inside that method that will catch any exception I throw. I'm basically attempting to do something twice, like ping a server, and if it fails the first time, catch the exception and try again, but if it fails the 2nd time, exit the entire method. is there an Initialize().Exit() I can implement? It doesn't seem like throwing an exception from an exception is the best way to do this. I want to catch if the initial ping fails or gets an error because sometimes the ping will fail and I have handling for attempting to connect to another server (not shown) if it does either of these.

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

Another example of a similar problem:

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.
        }
    }
}

I could theoretically NOT choose to do a void method and just have it return null and never assign the method to anything, but is that a better practice than a nested try catch?


Solution

  • If you have exception throw. Else return!

    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();
    

    and do it same wherever. So you can catch exceptions if occurs or method will stop where you want.