C# – Convention for Logging Within Nested Try Catch Blocks

cconventionsexception handlinglogging

I've looked at this question but it doesn't really help solve my dilemma.

System 1 calls system 2 within a try catch, the method in system 2 has it's own try catch, which sadly handles an exception but does not re-throw it. So my question is: Which system should log it? Each system has it's own logging files.

Sample:

Class System1{
Public void DoSomething(){
    Try{
        var sys = new System2();
        sys.ExecuteMethod();
    }
    Catch{Exception e){
        logger.log(e);
    }
}
}
// ------IN A DIFFERENT SYSTEM ON A DIFFERENT MACHINE------
Class System2{
Public void ExecuteMethod(){
    Try{
        throw new Exception("Test Excpetion");
    }
    Catch{Exception e){
        logger.log(e);
    }
}
}
}

Best Answer

If the system 2 handles the exception and doesn't rethrow it, then it sounds like system 1 doesn't have any way of knowing that an exception occurred. In that case, there's really no question as to whether system 1 should log anything, since it doesn't know an error occurred!

If both systems are aware of the error, and they are logging to different places, and the error is something you want logged, then you probably should have both of them log the error. You might want to think about finding a way to unify the logging though, as multiple log files are a pain to sift through (unless this is a client/server system where system 2 is running on a different machine than system 1, then you want to log in both places).

If system 2 is legitimately handling the error, then there is probably no need to log it in system 1. There might not even be a reason to log it in system 2 either, but you need to analyze whether that is required for your situation.

I would generally recommend that when in doubt, log it. But you definitely want to check at some point whether you are logging too much information, preferably before going to production.