为什么下面这段代码不合法?? class ExceptionA extends Exception {}
class ExceptionB extends ExceptionA {}
public class Test{
void thrower() throws ExceptionA{
throw new ExceptionA();
}
public static void main(String[] args){
Test t = new Test();
try{t.thrower();}
catch(ExceptionB e) {}
}
}
class ExceptionB extends ExceptionA {}
public class Test{
void thrower() throws ExceptionA{
throw new ExceptionA();
}
public static void main(String[] args){
Test t = new Test();
try{t.thrower();}
catch(ExceptionB e) {}
}
}
try {
t.thrower();
} catch (ExceptionB e) {
} catch (ExceptionA e) {
}因为还要catch ExceptionA e
飞过~~
throw new ExceptionB();
}
public static void main(String[] args) {
Q10 q10 = new Q10();
try {
q10.thrower();
} catch (ExceptionA e) {
e.printStackTrace();
}
}
public class ExceptionA extends Exception {
}
public class ExceptionB extends ExceptionA {
}
}
换成这样试试
LZ在thrower()方法中抛出的异常为ExceptionA, 在main方法里没有捕获, 所以就出错误了
throw new ExceptionB();
}
public static void main(String[] args) {
Q10 q10 = new Q10();
try {
q10.thrower();
} catch (ExceptionB e) {
e.printStackTrace();
}
}
public class ExceptionA extends Exception {
}
public class ExceptionB extends ExceptionA {
}
}
class ExceptionB extends ExceptionA {}
public class Test{
void thrower() throws ExceptionA{
throw new ExceptionA();
}
public static void main(String[] args) throws ExceptionB{
Test t = new Test();
try {
t.thrower();
} catch (ExceptionA e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ExceptionA extends Exception {}
class ExceptionB extends ExceptionA {}
public class Test{
void thrower() throws ExceptionA{
throw new ExceptionA();
}
public static void main(String[] args){
Test t = new Test();
try{t.thrower();}
/*catch只能捕获ExceptionA或Exception,不能捕获ExceptionA的子类ExceptionB,因为thrower()抛出的异常是ExceptionA*/
catch(ExceptionA e) {}
}
}
不能用子类去接收Exception啊