Is there an unhandled exception handler in Java?

前端 未结 5 1894
温柔的废话
温柔的废话 2020-12-03 08:00

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

相关标签:
5条回答
  • 2020-12-03 08:05

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

    0 讨论(0)
  • 2020-12-03 08:11

    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.

    0 讨论(0)
  • 2020-12-03 08:13

    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.

    0 讨论(0)
  • 2020-12-03 08:14

    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.

    0 讨论(0)
  • 2020-12-03 08:27

    Yes

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.html

    0 讨论(0)
提交回复
热议问题