首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Exception >

自定义异常unreachable statement

2014-01-26 
class Exception1 extends Exception { public Exception1( String msg ) { super( msg ) } } class Excep

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 " );
}

        

热点排行