aspose file tools*
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Why use UncaughtExceptionHandler?" Watch "Why use UncaughtExceptionHandler?" New topic
Author

Why use UncaughtExceptionHandler?

Dmitry Zhuravlev
Ranch Hand

Joined: Apr 14, 2010
Posts: 93
Greetings!

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.


S.D. MADHAN
Not many get the right opportunity !
Rohan Dhapodkar
Greenhorn

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
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why use UncaughtExceptionHandler?