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
{
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 Exception2( "Exception2" );
throw new Exception3( "Exception3" );
不能这样用啊!第一个THROW后不能再有其它语句了,因为方法中止了.
{
throw new Exception1( "Exception1" );
throw new Exception2( "Exception2" );
throw new Exception3( "Exception3" );
}
成员函数f()已经抛出Exception1,Exception2,Exception3,方法内又抛出一遍,不多余吗?
写不写都无所谓,不是它的问题。
如:
try{
}catch(Exception1 ex1){
```````````````````````
````````````````````执行体 throw new Exception1("message");
}catch(Exception2 ex2){
throw new Exception2("message");
}catch(Exception2 ex3){
throw new Exception3("message");
throw new Exception2( "Exception2" );
throw new Exception3( "Exception3" );执行第一条后 方法就会退出 后面两条没有执行的可能。
所以报错
如:
try{
}catch(Exception1 ex1){
```````````````````````
````````````````````执行体 throw new Exception1("message");
}catch(Exception2 ex2){
throw new Exception2("message");
}catch(Exception2 ex3){
throw new Exception3("message");
=============================================================================
看清楚了题目啊,老大:明明题目是要求:仅用一个catch子句捕获这三种异常
yifengtpf()的方法是可行的。public static void f() throws Exception1,Exception2,Exception3
{
throw new Exception1( "Exception1" );//以后的两行代码都是不可达代码
throw new Exception2( "Exception2" );
throw new Exception3( "Exception3" );
}
我目前把方法体的东西去掉了。只留下异常说明
public static void f() throws Exception1,Exception2,Exception3
{}
。暂时能通过编译