|
|
大家都知道在java开发中,我们可以用try catch来捕获异常,那么线程中出现了异常try catch 还依然管用吗?让我们一起先看个小例子吧。
package com.javazx.test.thread;0 H# }! A- T& I2 ]& q9 [! Z
import java.util.concurrent.ExecutorService;4 Z0 X! k3 d/ n' J0 Y; a
import java.util.concurrent.Executors;8 m; r: H) U/ ~
public class ExceptionThread implements Runnable { k6 [0 c( |8 I$ B2 b" \
public void run() {
throw new RuntimeException("线程内部出现异常");
}
/ y! G' P4 q3 D6 ~) \
public static void main(String[] args) {1 I+ L! L: ?' k, T% u9 a: F
try {
ExecutorService exec = Executors.newCachedThreadPool();/ w7 B% H- D, ]% q" r
exec.execute(new ExceptionThread());
} catch (RuntimeException e) {
System.out.println("能捕获到异常吗?");
}, r$ s, ?; A0 n- \0 V
}
}
运行结果呢?
Exception in thread "pool-1-thread-1" java.lang.RuntimeException: 线程内部出现异常
at com.javazx.test.thread.ExceptionThread.run(ExceptionThread.java:8)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) }3 {2 S0 J& L0 W' H* | Y9 P
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)4 P& r- Y4 @( C+ w$ T, Q2 n! B4 x
at java.lang.Thread.run(Thread.java:748)
答案已经很明显了,线程中是无法使用try catch来进行捕获的。那么如果要捕获异常呢 我们该怎么做呢?javase 1.5后我们是可以用UncaughtExceptionHandler来捕获异常的,具体要怎么做呢?大家还是看demo吧。 ]: O0 U. G7 M, |( H! e
1、
package com.javazx.test.thread;
public class ExceptionThread2 implements Runnable {
0 B" u5 A7 F! O- V4 `; R7 ^5 d" x
public void run() {% S* V9 Y# v! ], M& a8 ~6 k$ z. }! }
throw new RuntimeException("抛出运行时异常");
}8 P: ^" A* K5 Y$ E# _
} ^2 ~ j3 M B5 H
( _2 M* S! J$ l5 l3 G) D
2、 W9 C/ g& w" v$ |; M
package com.javazx.test.thread;# G+ w& F6 v$ X9 x: z( Q! I
: t, ]- c% P) Z3 `
public class MyUnchecckedExceptionhandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕获到异常:" + e);: P% _# J8 x. }6 v+ B
}
public static void main(String [] args){3 t3 W. n; j( C' u9 N( l/ ]
Thread t=new Thread(new ExceptionThread2());; S5 }( g" ^# J$ T
t.setUncaughtExceptionHandler(new MyUnchecckedExceptionhandler());: Z( F* _; e5 h& @! F/ C: \
t.start();
}; B. J3 J/ {1 m# b
}4 W9 H m2 t+ Y- T5 x
" b" V( ?/ @' C& N9 W
) |, _9 n# k P5 w0 x4 ?
运行结果:
捕获到异常:java.lang.RuntimeException: 抛出运行时异常 r: H# ]9 b r6 O* j7 Q8 @7 {5 a
终于捕获到了异常,大功告成!
|
|