Java Concurrency Learning eight--handling uncontrolled exceptions in a thread

Source: Internet
Author: User
Tags stack trace

This article is a summary of the study of the article on the network, thank you for your selfless sharing.

1 , Java in a 2 type of exception:

Check for exceptions: These exceptions must be forced to capture them or in a method throws clause.

No exception checked: These exceptions do not have to be forced to capture them.

2 , in a thread object's Run () method throws a check exception, we must capture and process them. Because the run() method does not accept the throws clause. When a non-check exception is thrown, the default behavior is to write the stack trace in the console and exit the program.

Package Chapter;public class Main8 {/** * <p> * </p> * @author Zhangjunshuai * @date 2014-8-21 pm 2:14:52 * @pa Ram args */public static void main (string[] args) {Task task = new Task (); Thread thread = new thread (Task); Thread.setuncaughtexceptionhandler (new Exceptionhandler ()); Thread.Start ();}}

Package Chapter;public class Task implements runnable{@Overridepublic void Run () {int numero = integer.parseint ("TTT");}}

Package Chapter;import Java.lang.thread.uncaughtexceptionhandler;public class Exceptionhandler implements uncaughtexceptionhandler{@Overridepublic void Uncaughtexception (Thread t, Throwable e) {System.out.printf ("an Exception has been captured\n "); System.out.printf ("thread:%s\n", T.getid ()); System.out.printf ("exception:%s:%s\n", E.getclass (). GetName (), E.getmessage ()); System.out.printf ("Stack traace"); E.printstacktrace (System.out); System.out.printf ("Thread status:%s\n", T.getstate ());}}

Operation Result:


Related Article

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.