user240141
user240141

Reputation:

How to catch and log exception inside Using statement without using try-catch?

As I know that Using statement has built in implementation of Dispose() and Try-Catch. So I want to know few things

  1. Is it possible to log an exception inside using statement without using try-catch block , either inside or outside the statement. If not, then why its built in to the statement.

  2. Nested or overuse of try-catch is not preferred, then why such model preferred to use.

            using (some_resource)
            {
                try
                {
                }
                catch
                {
                }
                finally
                {
                    //my exception logging mechanism
                }
            }
    

will become

            try
            {
                try
                {
                }
                catch
                {
                }
                finally
                {
                    //my exception logging mechanism
                }
            }
            catch
            {
            }
            finally
            {
                //some_resource.Dispose()
            }

Upvotes: 1

Views: 1576

Answers (2)

David Colwell
David Colwell

Reputation: 2590

Using compiles to Try{}Finally{}. See the following question: Does a C# using statement perform try/finally?

The reason for this is so that the resource will be disposed of regardless of if an exception is thrown. Resource disposal is the purpose of the using statement.

The correct implementation is:

using(Resource myresource = GetResource())
{
    try
    {}
    catch(Exception e)
    { //Maybe log the exception here when it happens?
    }
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062790

A using statement involves try/finally; there is no catch. But frankly, your concern is overkill; multiply-nested and complex try/catch/finally is "undesirable" because:

  • it makes the code hard to read
  • and even harder to get right (most people get it wrong, alas)
  • it is frequently misused
  • it suggests your method is doing too much

With using, this isn't an issue; it makes the intent very clean, without adding complexity or concern.

I would just use:

using (some_resource) {
    try {
        // some code
    } catch (Exception ex) {
        LogIt(ex);
        throw;
    }
}

Upvotes: 5

Related Questions