Java experience: handle exceptions that are not captured

Source: Internet
Author: User

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

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.