Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch and logging for irrelevant operations

Tags:

java

exception

I've a method to save timing information of each operation:

    public void queueTimerInfo(long start, long end, String msg) {
        try {
            timer.queue(start, end, msg);
        } catch (InterruptedException e) {
            Logger.info(e.getMessage());
        }
    }

I call the above method after each operation. What matters is the operation itself, whereas the timing is just a secondary task. That's why I decided not to do anything when the method fails, except logging it.

But I was always told that logging without managing the exception is a bad practice. So how should I rewrite the above code?

like image 276
user1883212 Avatar asked Sep 21 '15 11:09

user1883212


2 Answers

If you know the consequences, i.e. the timer.queue() call might be interrupted and not queue the data, and you can live with that, then it is OK to ignore the Exception. As with most rules, you need to know when to break them.

However, I would document your decision with a comment in the catch block, so that whoever maintains the code later knows that not handling the Exception was not an oversight, but a deliberate decision.

like image 139
Thomas Stets Avatar answered Oct 07 '22 01:10

Thomas Stets


But I was always told that logging without managing the exception is a bad practice

What does "managing" mean? Rethrowing them? Blindly following steps 1, 2, 3 because "zOMG an exception was thrown!!111"?

If you blindly follow best practices and other sorts of advice regardless of your context, then you'll probably end up with really problematic and awkward decisions. Don't do things just because it's best practice. Acknowledge the best practices, but at the same time make sure they actually make sense in your situation.

Ask yourself: does that exception make a difference? Does it break a contract? Does it change the flow of your application? Do you absolutely not want that to happen and if it does, then the situation is truly exceptional and you should really deal with it somehow?

If it doesn't make a difference and so on, then just logging it is perfectly acceptable. It really comes down to your context and to the significance of your exception.

LE: Of course, as Thomas suggests, you may want to document your decision.

like image 25
async Avatar answered Oct 07 '22 01:10

async