简体   繁体   中英

Is there an unhandled exception handler in Java?

If i remember correctly in .NET one can register "global" handlers for unhandled exceptions. I am wondering if there is something similar for Java.

Yes, there's the defaultUncaughtExceptionHandler , but it only triggers if the Thread doesn't have a uncaughtExceptionHandler set.

Yes, there is an 'almost' global such handler available in ThreadGroup . It is not as global as the one you are mentioning, but you can basically achieve the same functionality.

Starting with Java 5, there is a similar functionality available directly on the Thread class .

Often, Java frameworks like Struts and Spring (and the Servlet Spec, IIRC) allow you to set a global exception handler. These mechanisms are specific to each framework, though.

.NET Unhandled exception in Java:

Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler() {
  public void uncaughtException(Thread t1, Throwable e1) {
   // Exception handling code  
  }
});  

Stole it from here

Assuming it is like catch(...) in C++ you would do:

try
{
   // your code here
}
catch(Throwable ex)
{
   // any sort of exception, even if the VM has choked on a peanut
}

In general this isn't a good idea unless you are dealing with 3rd party code (you should try to always throw subclasses of Exception (and not RuntimeException) in your own code - unless it indicates a programmer error that should be delt with via unit testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM