File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Why use UncaughtExceptionHandler? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Why use UncaughtExceptionHandler?" Watch "Why use UncaughtExceptionHandler?" New topic

Why use UncaughtExceptionHandler?

Dmitry Zhuravlev
Ranch Hand

Joined: Apr 14, 2010
Posts: 93

Gentlemen, as we know, there is an UncaughtExceptionHandler, which can be introduced into the thread:

Could please explain, why this approach is more preferrable than just introducing a try-catch block which surrounds everything inside the run() method?

Madhan Sundararajan Devaki
Ranch Hand

Joined: Mar 18, 2011
Posts: 312

I believe, UncaughtExceptionHandler was introduced in JDK1.5, hence, prior to that the try-catch-finally was the only approach available.

Now that it is available from JDK1.5 onwards, you may use it to write compact code.

Not many get the right opportunity !
Rohan Dhapodkar

Joined: Jun 27, 2011
Posts: 23
Using try-catch block you handle the exception the way you want and probably you can re execute same job or can continue processing your code in same thread. But this is not case with UncaughtExceptionHandler. If you look at the javadoc for UncaughtExceptionHandler, uncaughtException() method will be executed when thread is abruptly terminated and you can't recover it. Probably you can use this method for auditing purpose. And may be after that your thread will be stopped.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

I would say the most important use is for threads for which you don't implement the Runnable yourself -- for example, when you're implementing a container or framework of some kind.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Why use UncaughtExceptionHandler?
It's not a secret anymore!