-2

We have a business-critical bit of legacy code, and the methods are relatively large and the code is a mess. Without a test framework and it being so critical our debugging abilities are limited. The logging messages are not useful - "object not set to an instance of an object"... somewhere in 500 lines of code that call other methods. This is because the method body is one big try/catch with specific exceptions being caught.

I want to propose that we address this with better error logging but I want to minimise my impact on the method. I need it to carry on as normal, because it is business critical. As such, people are scared to touch it so I need to check my understanding before I put the idea forward. As I say, I cannot just make a change and test it myself without writing a test harness. Which I don't have time to do due to firefighting, and it being last thing on a Friday.

I think a good way to do this is to insert smaller try/catch blocks inside the method body to catch all exceptions, log some USEFUL information, then rethrow to the specific catch handlers below.

public int SomeFunc()
{
    try
    {
        // many lines of code

        // I want to wrap this call that gives us problems
        try
        {
            BrittleFunc(arg1, arg2, ..., arg15);
        }
        catch (Exception e)
        {
            // Log the params for repro in unit test and then rethrow
            Log(args);
            throw;
        }

        // many more lines of code

    }
    catch(CustomException1 e)
    {
        // Do something
    }
    // more...
    catch(CustomException9 e)
    {
        // Do something
    }
    return someInt;
}

In my inner try/catch I COULD write specific catch handlers that match those at the bottom, but that will look messy.

If I catch CustomException2 inside a catch(Exception e) and rethrow, will it end up in catch(CustomException2 e) ?

VictorySaber
  • 3,084
  • 1
  • 27
  • 45
  • What is the purpose of the inner try/catch? In general, you should log at the highest possible level of your program. – John Saunders Jun 19 '15 at 17:05
  • 1
    You can just run the program you already have *once* and find out. It would have taken you a lot less time than you spent writing this question. – Servy Jun 19 '15 at 17:05

1 Answers1

0

Yes you can do that. Inside your first catch, the exception is simply treaded as the base Exception but when you rethrow it the next catch will catch it as it's real type.

When you rethrow the exception please use throw; not thrown ex; see here why

Community
  • 1
  • 1
Rémi
  • 3,867
  • 5
  • 28
  • 44