Java ThreadGroup .uncaughtException (Thread t, Throwable e)

Syntax

ThreadGroup.uncaughtException(Thread t, Throwable e) has the following syntax.

public void uncaughtException(Thread t,   Throwable e)

Example

In the following code shows how to use ThreadGroup.uncaughtException(Thread t, Throwable e) method.


public class Main {
  public static void main(String[] args) {
    ThreadGroupDemo tg = new ThreadGroupDemo();
/*from  w  w  w.j  a  va 2 s .  com*/
  }
}

class ThreadGroupDemo implements Runnable {
  public ThreadGroupDemo() {
    MyThreadGroup pGroup = new MyThreadGroup("ParentThreadGroup");
    MyThreadGroup cGroup = new MyThreadGroup(pGroup, "ChildThreadGroup");

    Thread thr2 = new Thread(pGroup, this);
    System.out.println("Starting " + thr2.getName());

    thr2.start();

    // create third thread
    Thread thr3 = new Thread(cGroup, this);
    System.out.println("Starting " + thr3.getName());

    thr3.start();

    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    thr2.interrupt();
    thr3.interrupt();

  
  }

  public void run() {
    try {
      System.out.print(Thread.currentThread().getName());
      System.out.println(" executing...");

      while (true) {
        Thread.sleep(500);
      }
    } catch (InterruptedException e) {
      Thread currThread = Thread.currentThread();
      System.out.print(currThread.getName());
      System.out.println(" interrupted:" + e.toString());

      // rethrow the exception
      throw new RuntimeException(e.getMessage());
    }
  }
}

class MyThreadGroup extends ThreadGroup {

  MyThreadGroup(String n) {
    super(n);
  }

  MyThreadGroup(ThreadGroup parent, String n) {
    super(parent, n);
  }

  public void uncaughtException(Thread t, Throwable e) {
    System.out.println(t + " has unhandled exception:" + e);
  }
}




















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable