Source: csdn Author: enoeht
Not all exceptions are caught in our program. Some of them are because we don't want to capture them, because we don't think they need to be captured.
Some of them cannot be captured, because we cannot determine where they will appear, such as RuntimeException such as NullPointerException, ClassCastException, and IndexOutOfBoundsException. We may capture them wherever they happen, but this is a really bad solution. However, in some cases, we must do some things when some uncaptured exceptions occur, such as releasing resources and leaving the program in the wrong state.
Here, we solve this problem through a method provided by ThreadGroup, so that our program can become more robust. ThreadGroup provides an uncaughtException callback method. When an uncaptured exception occurs in a thread group, the JVM will call this method.
|
Public class ApplicationLoader extends ThreadGroup {
Private ApplicationLoader (){
Super ("ApplicationLoader ");
}
Public static void main (String args [])
{
Runnable addStarter
= New Runnable (){
Public void run (){
// Call the entry function of our program here
// MyApplication. main (args );
}
};
// Run our own program as a thread in this thread group
New Thread (new ApplicationLoader (),
AddStarter). start ();
} |
/* When a thread stops due to an uncaptured exception, this method will be called by the virtual machine. We only need to override this method in our ThreadGroup subclass, handle exceptions accordingly */
|
Public void uncaughtException (Thread threadf, Throwable
E ){
// Handle the Exception
}
} |