0

We have a piece of code for reading from queue

while(true){ try { message = readMessageFromQueue(); processMesage(message); //Writes into DB and some other operation }catch(Exception e) { log the exception } } 

Now there are ten threads which are spawned using executor service with the aim of running forever. However we have noticed after sometime we deploy(it can be 10-15 days or month) the number of thread is getting reduced(Write per second is also decreasing because of that).

The question is should we catch Error or only exception in the code which we want to run forever like this and is catching Exception can cause this problem ?

1
  • What's inside processMessage()? It's common mistake that you leave the thread/connection/transaction open if exception is thrown (it should be closed in processMessage() in finally{} section). It may cause observed issue. Commented Jan 29, 2015 at 7:48

4 Answers 4

2

Yes, it's better to catch a Throwable there, not just Exception. Depending on your processing you might get, for example, a StackOverflowError that will kill your thread without logging. You might not be able to recover from it, but at least you can debug the problem latter.

Sign up to request clarification or add additional context in comments.

Comments

0

From what I understand, you're asking if it is okay to catch by general Exception versus specific exceptions, like ArrayOutOfBoundsException. So, I guess my answer come down to whatever you prefer. You can catch by Exception, which isn't usually advised because you should always know what your code is doing and thus what could go wrong, but it does accomplish your tasks. Now, the reason you should catch by specific exceptions is that you can have different methods of handling different errors. Maybe the way you are handling the error isn't universally applicable to all errors, so when the thread sees an exception it isn't designed to expect, it crashes leaving you with one less thread.

Comments

0

I prefer catching specific exceptions of I can do something gracefully with that failure (like retry or do some default behavior). But if an exception means the program can't continue at all regardless, than catching the most generic exception and terminating is fine.

Comments

0

catching Exception is a "shotgun" approach to exception handling - "Whatever exception you will throw, I will catch it!".

catching a specific, ideally custom Exception is preferred mainly because you know where that exception is thrown, and you can gracefully handle that exception, or do some methods specifically for a certain exception. Therefore gives you more control of your application.

hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.