omsharp
omsharp

Reputation: 353

Nested try/catch. Is it Ok?

This code is called in a BackgroundWorker's DoWork event handler, I am creating a WCF client and using it in the try block, if there is an exception I want to abort and retry for 5 times before returning from the handler.

    private void WorkerDoWork(object sender, DoWorkEventArgs e)
    {            
        var mmc = new ServiceClient();

        try
        {
            e.Result = mmc.SubmitData(measure);
        }
        catch (Exception)
        {
            mmc.Abort();

            mmc = new ServiceClient();

            var counter = 0;

            while ((bool)e.Result == false && counter++ < 5)
            {
                try
                {
                    e.Result = mmc.SubmitData(measure);
                }
                catch (Exception)
                {
                    mmc.Abort();
                    mmc = new ServiceClient();
                }
            }
        }
        finally
        {
            if (mmc.State == CommunicationState.Faulted)
            {
                mmc.Abort();
            }
            else
            {
                mmc.Close();
            }
        }
     }

I am not realy happy with the code, feels like something is fishy with it! Specially the nested try/catch.

Is this code ok? or should I refactor it?

Upvotes: 0

Views: 136

Answers (1)

Gerard Sexton
Gerard Sexton

Reputation: 3210

Yes, I agree the hammering of the web service blindly is the problem.

It is good to know what possible exceptions you can handle.

This looks like you are only dealing with an unreachable endpoint when you could instead be getting a warning about data format, types, limits, restrictions, authentication failure, account usage limit hits, ANYTHING!

But eveything is treated like a retry would fix it, and if it doesn't, it's broke!

How about some reporting on the problems encountered?

As a good programmer, you should find out what exceptions will be thrown for what situations and handle them, if you can, in an appropriate manner.
If you cant handle them, then report them to logging or to the user (if it is interactive).

Upvotes: 2

Related Questions