简体   繁体   中英

Handling Exceptions in while loops

I want to log an error message in my application for a retry to call out the webservice but I only want to disply the error message once outside of the while loop instead of logging the error everytime it retries and fails or should I do a do while loop.

int retryCount = x;
int retryWait = y;

int retry = 0;

while (retry <= retryCount)
{
    try
    {
        //get response
    }
    catch (InvalidOperationException invalid)
    {
        message = //display status message 
    }
    catch (Exception exc)
    {
        //display log message 
        //retry again 
        retry++;

    }
    message = "Mamium tries have been exceeded
    Logs.WriteError(message);
    return false;
}

Simply reset the message, and check if there is one, so something like:

    while (retry <= retryCount)
    {
        try
        {
            message = null;
            //get response
        }
        catch (InvalidOperationException invalid)
        {
            message = invalid.Message; //display status message 
        }
        catch (Exception exc)
        {
            //display log message 
            //retry again 
            message = exc.Message; //display status message 
            retry++;

        }

        if (!string.IsNullOrEmpty(message))
        {
            message = "Mamium tries have been exceeded"
            Logs.WriteError(message);
            return false;
        }
    }

You could use your retry and retryCount variables, for sample, and use finally block to increment anyway.

{ // main scope

    int retry = 0, retryCount = 3;
    string message = null;

    while (retry < retryCount)
    {   
        try
        {
            //get response      
        }
        catch (Exception exc) 
        {
            //any error, since you don't need to give another threatment for other erros, just use  Exception

            message = exc.Message;
        }
        finally
        {   
            // increment retry anyway
            retry++;
        }
    }

    if (retry >= retryCount)
    {
        message = "Mamium tries have been exceeded"
        Logs.WriteError(message);
        return false;
    }       

    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM