1

Should one log success of an operation within a try-catch-block, or after it?

Example:

try
    do x
    log('successful')
catch
    log('fail')
end

or is this better:

try
    do x
catch
    log('fail')
end
log('successful')

I would say that a logger should never fail, but what if, for some reason, it does anyway?

In this specific case, I had a logfile on a network drive which disconnected due to actions of do(x), which however did not fail -- obviously my try failed, but my operation worked. However, I find the latter example harder to read, and I try to keep my code as tight as possible for readability.

1
  • In general, try and catch blocks should be as concise and focused as possible.
    – user22815
    Aug 13 '14 at 20:54
4

First of all, you have to ensure that logging never throws any exceptions. It's better not to log one message than breaking program logic by it.

Besides that, your second code in case of a success would log:

"successful"

but an error would log 2 messages:

"fail"
"successful"

I think it's not what you want, so a first example is the way to go.

1
  • Thanks! Your point with logging two messages makes it obvious :D
    – zuiqo
    Aug 18 '14 at 15:02
2

I would say that a logger should never fail, but what if, for some reason, it does anyway?

That makes in your scenario no sense:

try
    do x
    log('successful')
catch
    log('fail')
end

If your first logger fails, an exception is thrown and you are going to the catch block. But if the logger fails in the first place, it would do so in the second place. If one takes your path you would have to write an infinite amount of try-catch if you want to make sure one of the loggers throws an exception and also an infinite amount of logger.

Your second approach is misleading as others have written.

Though it makes sense doing it the first way: but with different log-levels:

try
    do x
    log.info('operation successful')
catch
    log.error('something went terribly wrong') #or log.warn()
end

But there is another programming paradigm, which is helpful: http://en.wikipedia.org/wiki/Aspect-oriented_programming With AOP you could separate your concerns better.

1

To answer your question you really need to answer the following: would you treat a log call failure as a failure of the whole try block? If yes, then it belongs in there. Otherwise, it should be placed outside. The bigger idea is to manage granularity of the try blocks, so that you catch right set of exceptions.

Not the answer you're looking for? Browse other questions tagged or ask your own question.