- 2010-01-21 04:24
- Java
在线程启动后,很可能出现预计外的异常。比如RuntimeException,一般我们在程序中很少捕捉这种异常,但一旦出现,我们很希望在Log文件里能看到异常,这样的分析程序就会方便很多。
在Java中,可以通过setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler e)来实现对未捕捉的异常进行处理。其中UncaughtExceptionHandler的实例必须实现uncaughtException函数。在uncaughtException(Thread t, Throwable e)中实现用异常的处理。
如下程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.lang.Thread.UncaughtExceptionHandler; public class UncaughtExceptionTest { public static void main(String[] args) { Thread tt = new Thread() { @Override public void start() { int[] t = new int[1]; for (int i = 0; i < 2; i++) { System.out.println(t[i]); } } }; Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(e); } }); tt.start(); } } |
程序结果如下:
1 2 | 0 java.lang.ArrayIndexOutOfBoundsException: 1 |
- Newer: PHP学习(1) 词法结构
- Older: Java文件列表的方法
Comments:0
发表评论
Trackbacks(0)
http://yutuo.net/posts/20.html/trackback