008 The research of thread abnormality

Source: Internet
Author: User

I. Overview

We know that once a thread is running, it will open another line Cheng to complete its own task, when the exception capture is a problem.

Two. Presentation of the exception

 Public Static void Main (string[] args) {        try  {            new Thread (new  Runnable () {                @Override                  Public void run () {                    thrownew  runtimeexception ();                }            }). Start ();         Catch (Exception e) {            e.printstacktrace ();        }    }

We run the above procedure with the following results:

inch " Thread-0 " java.lang.RuntimeException at    com.trek.concurrency.exception.exceptiontest$1. Run ( Exceptiontest.java:at    java.lang.Thread.run (thread.java:745)

We found that we simply could not catch the exception thrown by a thread, simply printing the stack information of a thread.

Three. To complete a task using the thread exception handler

 Public classExceptionhandler {Static classHandler implements uncaughtexceptionhandler{@Override Public voiduncaughtexception (Thread T, Throwable e) {//all we need to do is print the information here.System. out. println ("the name of the thread:"+t.getname ()); System. out. println (e); }    }         Public Static voidMain (string[] args) {thread thread=NewThread (NewRunnable () {@Override Public voidrun () {Throw NewRuntimeException ("I threw out an exception message");        }                    }); Thread.setuncaughtexceptionhandler (NewHandler ());    Thread.Start (); }}

First, we define an inner class as the exception handler.

We then bind an instance of the exception handler object when creating the thread.

When our thread throws an exception, the exception handler catches the exception.

We look at the results:

Thread Name: thread-0java.lang.RuntimeException: I threw out an exception message

We find that the exception information thrown by the thread we can capture.

008 The research of thread abnormality

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.