日期:2014-05-20  浏览次数:20848 次

大家看下我这个程序:同是抛出和捕获多个自定义异常
class   Exception1   extends   Exception
{
public   Exception1(   String   msg   )
{
super(   msg   );
}
}

class   Exception2   extends   Exception
{
public   Exception2(   String   msg   )
{
super(   msg   );
}
}

class   Exception3   extends   Exception
{
public   Exception3(   String   msg   )
{
super(   msg   );
}
}

public   class   Test7
{
public   static   void   f()   throws   Exception1,Exception2,Exception3
{
throw   new   Exception1(   "Exception1 "   );
throw   new   Exception2(   "Exception2 "   );
throw   new   Exception3(   "Exception3 "   );
}

public   static   void   main(   String[]   args   )
{
try
{
f();
}
catch   (   Exception   e   )
{
e.printStackTrace();
}
}
}

编译显示:unreachable   statement

------解决方案--------------------
throw new Exception1( "Exception1 " );
throw new Exception2( "Exception2 " );
throw new Exception3( "Exception3 " );
不能这样用啊!第一个THROW后不能再有其它语句了,因为方法中止了.

------解决方案--------------------
public static void f() throws Exception1,Exception2,Exception3
{
throw new Exception1( "Exception1 " );
throw new Exception2( "Exception2 " );
throw new Exception3( "Exception3 " );
}
成员函数f()已经抛出Exception1,Exception2,Exception3,方法内又抛出一遍,不多余吗?
------解决方案--------------------
题目的意思是让你在那个方法里 先捕获这3种异常 然后再抛出
如:
try{
}catch(Exception1 ex1){
```````````````````````
````````````````````执行体

throw new Exception1( "message ");
}catch(Exception2 ex2){
throw new Exception2( "message ");
}catch(Exception2 ex3){
throw new Exception3( "message ");
------解决方案--------------------
throw new Exception1( "Exception1 " );
throw new Exception2( "Exception2 " );
throw new Exception3( "Exception3 " );

执行第一条后 方法就会退出 后面两条没有执行的可能。
所以报错
------解决方案--------------------
to lz:题目要求的是main函数里只能用一个catch,没说f()里面只能用一个catch子句
yifengtpf()的方法是可行的。

public static void f() throws Exception1,Exception2,Exception3
{
throw new Exception1( "Exception1 " );//以后的两行代码都是不可达代码
throw new Exception2( "Exception2 " );
throw new Exception3( "Exception3 " );
}