1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.util;
21
22 /***
23 * The root thread group. Used to handle all uncaught exceptions that
24 * occur at any child thread of the group.
25 *
26 * <p>If you want to catch all uncaught exceptions in your application,
27 * use the following code snippet:
28 *
29 * <p><pre>
30 * public static void main(final String[] argv) {
31 * RootThreadGroup tg = new RootThreadGroup("RootThreadGroup",
32 * new ErrorHandler());
33 * Thread mainRunner = new Thread(tg, "XNapMain") {
34 * public void run() {
35 * runMain(argv);
36 * }
37 * };
38 * mainRunner.start();
39 * }
40 *
41 * public static void runMain(final String[] argv) {
42 * // run the actual main code
43 * }
44 * </pre>
45 */
46 public class RootThreadGroup extends ThreadGroup {
47
48 private UncaughtExceptionListener listener;
49
50 public RootThreadGroup(String name, UncaughtExceptionListener listener,
51 boolean installAsAWTExceptionHandler)
52 {
53 super(name);
54
55 this.listener = listener;
56
57 if (installAsAWTExceptionHandler) {
58 installAsAWTExceptionHandler();
59 }
60 }
61
62 public RootThreadGroup(String name, UncaughtExceptionListener listener)
63 {
64 this(name, listener, true);
65 }
66
67 /***
68 * Invoked by the AWTEventQueue in case of an unhandled exception.
69 * @param e the uncaught exception
70 * @see #installAsAWTExceptionHandler()
71 */
72 public void handle(Throwable e)
73 {
74 listener.uncaughtException(Thread.currentThread(), e);
75 }
76
77 /***
78 * Installs this class as the awt exception handler.
79 */
80 public void installAsAWTExceptionHandler()
81 {
82 System.setProperty("sun.awt.exception.handler",
83 "org.xnap.commons.util.AWTExceptionHandler");
84 }
85
86 /***
87 * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
88 * java.lang.Throwable)
89 */
90 public void uncaughtException(Thread t, Throwable e)
91 {
92 listener.uncaughtException(t, e);
93 }
94
95 }