Home  >  Article  >  Java  >  Example of catching sub-thread exceptions in java multi-thread programming

Example of catching sub-thread exceptions in java multi-thread programming

高洛峰
高洛峰Original
2017-01-18 14:53:581916browse

You cannot catch child thread exceptions through try catch. The Thread object provides the setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) method to obtain exceptions generated in the thread.

package threads;
import java.lang.Thread.UncaughtExceptionHandler;
public class TextException
{
  public static void main(String[] args)
  {
    Test test = new Test();
    test.setUncaughtExceptionHandler(new UncaughtExceptionHandler()
    {
      public void uncaughtException(Thread t, Throwable e)
      {
        System.out.println(t.getName() + " : " + e.getMessage());
        // TODO
      }
    });
  }
  public static class Test extends Thread
  {
    public Test()
    {
    }
    public void run()
    {
      throw new RuntimeException("just a test");
    }
  }
}

For more articles related to Java multi-threaded programming examples of catching sub-thread exceptions, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn