Java Multithreading exception Handling

Source: Internet
Author: User
Tags call back try catch

In a Java multithreaded program, all threads are not allowed to throw uncaught checked exception, which means that each thread needs to dispose of its own checked exception . This is constrained by the Java.lang.Runnable.run () method declaration (because there is no throws Exception section on this method declaration). However, threads are still likely to throw unchecked exception, and when such exceptions run out, the thread will end up completely unaffected for the main thread and other threads and will not be fully aware of the exception thrown by a thread ( It is also said to be completely unable to catch this exception ). This design of the JVM stems from the idea that "threads are pieces of code that are executed independently, and that the thread's problem should be solved by the thread itself rather than being delegated to the outside." "Based on this design philosophy, in Java, the exception of threading methods (either checked or unchecked exception) should be try catch and disposed of within the bounds of the thread code (within the Run method).

 Public classExeceptionthreadImplementsRunnable {@Override Public voidrun () {Throw Newruntimeexception (); }     Public Static voidMain (string[] args) {Try{executorservice exec=Executors.newcachedthreadpool (); Exec.execute (NewExeceptionthread ()); } Catch(Exception e) {//Cannot capture System.out.println ("Exeception has handled"); }    }}
Exception in Thread "Pool-1-thread-1" java.lang.RuntimeException at    Thread.Exection.ExeceptionThread.run ( Execeptionthread.java:at    java.util.concurrent.ThreadPoolExecutor.runWorker (Unknown Source)    At Java.util.concurrent.threadpoolexecutor$worker.run (Unknown source) at    Java.lang.Thread.run (Unknown source) 

But if the thread does not have its own try catch a unchecked exception, and we want to catch and handle the exception outside of the line code boundary (outside the Run method) , Java provides us with a callback mechanism that allows exceptions to be handled outside of the thread code boundary when an exception occurs in the threads, that is, the setuncaughtexceptionhandler provided by the thread object ( Thread.uncaughtexceptionhandler eh) method.

This method sets a Uncaughtexceptionhandlerfor a thread to ensure that the public void of the Uncaughtexceptionhandler interface can be passed through the callback when the thread has an exception The uncaughtexception (thread T, Throwable e) method handles exceptions, such that the benefit or purpose is to be outside the bounds of the thread code (outside of the Run () method), where there is a place to handle uncaught exceptions. However, it is particularly clear that although the exception is handled in the callback method, the callback method is still in the thread that throws the exception when it executes! It is also important to note that if a thread is created through the thread pool, the Uncaughtexceptionhandler interface does not necessarily immediately call back when a thread exception occurs.

classExceptionThread2ImplementsRunnable { Public voidrun () {Thread T=Thread.CurrentThread (); System.out.println ("Run () by" +t); System.out.println ("Eh=" +T.getuncaughtexceptionhandler ()); Throw Newruntimeexception (); }}classMyuncaughtexceptionhandlerImplementsThread.uncaughtexceptionhandler {@Override Public voiduncaughtexception (Thread T, Throwable e) {System.out.println ("Caught" +e); }}classHandlerthreadfactoryImplementsthreadfactory {@Override PublicThread Newthread (Runnable R) {System.out.println ( This+ "Creating new Thread"); Thread T=NewThread (R); System.out.println ("Created" + t + "ID:" +T.getid ()); T.setuncaughtexceptionhandler ( New Myuncaughtexceptionhandler ()); System.out.println ("Eh=" +T.getuncaughtexceptionhandler ()); returnT; }} Public classcaptureuncaughtexception { Public Static voidMain (string[] args) {Executorservice exec=executors. Newcachedthreadpool (Newhandlerthreadfactory ()); Exec.execute (NewExceptionThread2 ()); }}
New threadcreated thread[thread-0,5,main] Id:9eh=[email protected]run () by Thread[thread-0,5, Main]eh=[email protected][email Protected]new  threadcreated thread[thread-1,5,main] id:11eh=[email protected] Caught Java.lang.RuntimeException

Default mode:

 public  class   Settingdefaulthandler { static  void   main (string[] args) {thread.setdefaultuncaughtexceptionhandler (  new   Myuncaughtexceptionhandler ());//thread default exception trap class  Executorservice Exec=executors.newcachedthreadpool ();    Exec.execute ( new   ExceptionThread2 ()); }}
Run () by thread[pool-1-thread-1,5, Main]eh=java.lang.threadgroup[name=main,maxpri=10]caught Java.lang.RuntimeException

Compared to the above method, there is also a programmatic way to learn, that is, sometimes the caller of the main thread may just want to know what happened during the execution of the child thread, not necessarily processing or immediate processing, Then the method that initiates the child thread can collect the exception instance thrown by the thread to return to the caller as a exception list, which is called by the towners to decide how to respond according to the exception condition. However, it is important to note that this time the child thread is terminated early.

Java thread is a strange part of the exception. General Online thread Encounter checked exception, recommended practice is to use the Try/catch block to deal with. For unchecked exception, a more reasonable way is to register an object instance that implements the Uncaughtexceptionhandler interface to handle.

Reference: http://www.cnblogs.com/zhuawang/p/3751875.html

http://blog.csdn.net/bluishglc/article/details/8216824

Java Multithreading exception Handling

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.