0

I've a thread that sometimes just dies silently and I want to surround the operation with a try/catch block to find out what is going on without killing the thread.

I initially surrounded the operations within run with a try / catch (Exception e) block but the concern was that this may overlook a checked exception getting thrown by a dependency of run() and not be handled properly. On the other hand, I'm worried about (unchecked) Errors getting swallowed as well.

Someone suggested that as a short-term defense, I should rename the current run() method to something like runInternal(), with no checked exceptions declared, and put the catch/log Throwable in run() around a call to runInternal().

I don't understand how would that help.

user1071840
  • 3,522
  • 9
  • 48
  • 74
  • hmm, I don't think that makes any difference, you are just moving a block of code to another method... – nafas Jun 04 '15 at 15:56
  • Have you tried using an UncaughtExceptionHandler? – Necreaux Jun 04 '15 at 16:10
  • I always put a try/catch around all the code in the run() method. Without that, when an exception thrown it will kill the thread. It would be better to log it at that point, at least you will see what happened, and can correct it, and the thread will stay alive. I haven't used UncaughtExceptionHandler, but the java docs say it gets called when the tread terminates, so if you don't what the thread to terminate, you probably don't want to use that. – Alper Akture Jun 05 '15 at 18:10

1 Answers1

1

I want to surround the operation with a try/catch block to find out what is going on without killing the thread.

quick answer: you can't save the thread. once an exception is thrown, the most you can get as an outsider is the stack trace.

The wrapping with runInternal technique will help you log the stack trace of the error, instead of having the thread die silently.

However, what you really want to do here, is to attach a debugger, like eclipse, and set it up to pause on caught and uncaught exception until you find the one you're looking for. That will pause the thread at the point of the fault, without killing it yet.

Break when exception is thrown

Community
  • 1
  • 1
Lorenzo Boccaccia
  • 6,041
  • 2
  • 19
  • 29