javaexceptiontry-finally

alternative to try finally for logging in Java


Many methods in my code I am currently working on follows a certain pattern:

public void aMethod(...) throws CustomException {
    Log("aMethod Started")
    try {
        //Many method calls that could throw a CustomException
    } finally {
        Log("aMethod Ended")
    }
}

Changing anything about the CustomException is not an option.

Is there any better alternative that doesn't work with try finally?


Solution

  • I would say

    finally {
        Log("aMethod Ended")
    }
    

    is not good way to log ending of method. If an exception occurred the method has not actually ended but interrupted and returned without completing.

    So, the "Log("aMethod Ended")" shall be outside of finally. If end logger is missing in that log, you will anyway get from the exception stack trace.

    If you want to just log weather the method was called and then left, then Spring AOP is what could be implemented for the whole product configuration, so you wont need to duplicate the logger everywhere.

    On the other hand, if you personally feel this logger wont be of much use and just redundant information; then just turn off that rule in solar lint configuration.