Nested try/catch blocks to give 2 attempts on an operation

Discussion in 'C++' started by beta2000, Aug 9, 2005.

  1. beta2000

    beta2000 Guest

    I want to try Refresh() again if the first Refresh() fails. Code:

    try
    {
    try
    {
    Refresh(); // ... first attempt...
    }
    catch(...)
    {
    Refresh(); // ... second attempt...
    }
    }
    catch(...)
    {
    // Display error message (both attempts failed)
    }

    My question is -- Is this a good style? Is there a way to not use so
    many try/catch and still attempt the operation up to 2 times?
     
    beta2000, Aug 9, 2005
    #1
    1. Advertisements

  2. I think it would be better to have a loop

    bool go_on = true;
    int attempt = 0, total = 2;

    while (go_on) {
    try {
    Refresh();
    go_on = false; // if manages to get here, no need to repeat
    }
    catch(...) { // whatever you catch
    go_on = ++attempt < total;
    if (go_on)
    do_something_to_set_up_another_attempt(attempt);
    }
    }

    if (attempt == total)
    // all attempts failed

    That way you can control the number of attempts much easier.

    V
     
    Victor Bazarov, Aug 9, 2005
    #2
    1. Advertisements

  3. beta2000

    red floyd Guest

    You could use a loop. That also allows you easily change the number of
    tries.

    const int tries = 2;
    int j; // deliberately outside the loop
    for (j = 0; j < tries ; ++j)
    {
    try
    {
    Refresh();
    break;
    }
    catch(...)
    {
    /* do nothing */
    }
    }

    if (j >= tries)
    {
    // have a panic attack, all tries failed
    }
     
    red floyd, Aug 9, 2005
    #3
  4. * :
    Not in C++.

    void RefreshWithRetry()
    {
    try{ Refresh(); }
    catch( std::exception const& ) { Refresh(); }
    }

    ....
    try
    {
    RefreshWithRetry();
    }
    catch( std::exception const& x )
    {
    // Display error message (both attempts failed)
    }

    If you want a more general solution you could use a loop, and if you want a
    still more general solution you could generalize that to a class with the
    action performed by a virtual function.
     
    Alf P. Steinbach, Aug 9, 2005
    #4
  5. beta2000

    beta2000 Guest

    Building on this idea, I did something similar (which uses one less
    variable :p)...

    int tries = 2;
    while ( tries > 0 )
    {
    try
    {
    Refresh();
    break;
    }
    catch(...)
    {
    --tries;
    }
    }

    if ( tries == 0 )
    ShowMessage("Error");
     
    beta2000, Aug 9, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.