关于异常处理的问题

ylovegm 2008-04-17 01:56:28
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未捕获到?
...全文
92 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Shine_Panda 2008-04-18
  • 打赏
  • 举报
回复
throw new ExceptionX() 语句。
可以认为 相当于一个 return 语句。
一旦执行后面的代码无论什么finally也好都不会执行。


public void f() throws Exception{
throw new Exception();
System.out.println ("aaaa");

}
这样的函数编译都是通不过的。
因为throw new Exception();就相当于一个return 后面的代码是无法执行的。
xfc1014 2008-04-17
  • 打赏
  • 举报
回复
这个问题真难,能不能请高手们讲的更详细。
anqini 2008-04-17
  • 打赏
  • 举报
回复
你在finally块上重新抛出throw new MyException2(s2); 这个了,所以把之前的没跑出来,一次只能throw一次的!
Dan1980 2008-04-17
  • 打赏
  • 举报
回复
头一回看到这么用异常的。楼主真奇思妙想也!

第三种情况中,第一个异常还没来得及抛出,第二个异常又抛出来了,所以第二个异常“覆盖”了第一个异常,最终抛出的是第二个异常。

ps. 你想让一个方法中同时抛出两个异常,那是不可能的。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧