2

Its absolutely clear for me, that usually a Java program should not catch Throwable, since it is catching Error-s like OutOfMemoryError. 100% clear.

But.

If I have a multi-threaded application, it is usually a best practice, that I should have an UncaughtExceptionHandler, which does something if RuntimeException or Error happens. What I usually want to do, is simply logging. Logging RuntimeExceptions cannot really hurt, thats clear. But the question arises in me:

Which errors can I catch and log safely in an UncaughtExceptionHandler, which will not treat my whole application if I log it? Which errors are there, which does not mean, that the application must stop immediately?

For example if I get an OutOfMemoryError, I would just ask for a printStackTrace to standard out, since the memory need of logging it can kill other threads. But a StackOverflowError seems to me totally safe to be logged, since it means simply, that the stack area of the current thread became full. It is safe to log it. Which other Error descendants would you log?

Gábor Lipták
  • 9,646
  • 2
  • 59
  • 113

1 Answers1

1

Any Throwable is safe to catch if you can do something constructive with it. Any Throwable where you can't do something useful, should not be caught.

BTW: For catch all logging, I catch(Throwable) for logging purpose when I know the remaining code would otherwise discard the Throwable/Error/Exception.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130