在做练习是遇到个问题public class Test2 extends Thread {
Object object = new Object();
public static void main(String[] args){
Test2 test = new Test2();
test.start();
}
public void run(){
try {
object.wait();
}
catch (Exception e) {
}
System.out.println("123");
}
}上面是代码
就是在Catch(Exception e) 这里 会抛出异常但是还要打印“123”,
但如果把Exception换成InterruptedException就可以抓住抛出的异常,而不打印“123”
我觉得Exception 是 InterruptedException的superclass可以抓住所有checked exception。
请大家执教
Object object = new Object();
public static void main(String[] args){
Test2 test = new Test2();
test.start();
}
public void run(){
try {
object.wait();
}
catch (Exception e) {
}
System.out.println("123");
}
}上面是代码
就是在Catch(Exception e) 这里 会抛出异常但是还要打印“123”,
但如果把Exception换成InterruptedException就可以抓住抛出的异常,而不打印“123”
我觉得Exception 是 InterruptedException的superclass可以抓住所有checked exception。
请大家执教
在你catch Exception的时候,异常被捕获到,然后执行catch中的语句,再之后继续向下执行,所以打印了“123”。你可以好好的看下try catch的作用,java的路很长很坎坷的,一路好走
谢谢楼上的解答哈有一点不是很明白 你说异常捕获了反而接着执行下面的语句。 不是应该发现异常后马上中止线程吗?
我试了试把run 改写
public void run(){
try {
object.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("123");
}"123" 仍然被打印。 你能帮忙解释详细些吗 谢谢
try {
object.wait();
Thread t = new Thread();
//t.sleep(2000);
} catch (InterruptedException ie){
System.err.println("ie");
} catch (IllegalMonitorStateException imse){
System.out.println("imse");
}//捕捉这个异常就可以了
System.out.println("123");
}