Search code examples
c#.netexceptiontry-catchusing

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

Solution

  • 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;
        }
    }