package test;
/**
 * 根据参数的不同,打印出参数错误信息
 *
 */
class MyException1 extends Exception{
String s;
MyException1(String s){
this.s = s;
}

public String toString(){
s = s+"第一个参数错误";
return s;
}
}
class MyException2 extends Exception{

String s;
MyException2(String s){
this.s = s;
}

public String toString(){
s = s + "第二个参数错误";
return s;
}
}public class NumberAdd {
static public int add(String s1, String s2) throws MyException1,MyException2 {

int a;
int b;
int sum;
try{
a = Integer.parseInt(s1);

}catch(NumberFormatException e){

throw new MyException1(s1);

}finally{
try{

b = Integer.parseInt(s2);

}catch(NumberFormatException e){

throw new MyException2(s2); }
}
sum  = a + b;
return sum;
}

//测试方法,分别测试以下三中情况
public static void main(String[] args){
try {
int sum = add("123","321");
System.out.println(sum);
} catch (MyException1 e) {
System.out.println(e.toString());
} catch (MyException2 e) {
System.out.println(e.toString());
}

try {
int sum = add("abc","123");
System.out.println(sum);
} catch (MyException1 e) {
System.out.println(e.toString());
} catch (MyException2 e) {
System.out.println(e.toString());
}

try {
int sum = add("aaa","bbb");
System.out.println(sum);
} catch (MyException1 e) {
System.out.println("1");
System.out.println(e.toString());
} catch (MyException2 e) {
System.out.println("2");
System.out.println(e.toString());
}

}
}
结果如下:
444
abc第一个参数错误
2
bbb第二个参数错误
在测试方法中,为什么在最后一个try...catch...catch...中对于出现的MyException1未捕获到?

解决方案 »

  1.   

    你在finally块上重新抛出throw new MyException2(s2); 这个了,所以把之前的没跑出来,一次只能throw一次的!
      

  2.   

    throw new ExceptionX() 语句。
    可以认为 相当于一个 return 语句。
    一旦执行后面的代码无论什么finally也好都不会执行。象 
    public void f() throws Exception{
    throw new Exception();
    System.out.println ("aaaa");

    }
    这样的函数编译都是通不过的。
    因为throw new Exception();就相当于一个return  后面的代码是无法执行的。