class ThreeException extends Exception { }
public class FinallyWorks {
static int count = 0;
/** Creates a new instance of FinallyWorks */
public static void main( String args[] ) {
while( true ) {
try {
if( count++ == 0 )
throw new ThreeException( );
System.out.println( "No Exception" );
} catch( ThreeException e ) {
System.err.println( "ThreeException" );
} finally{
System.err.println( "In finally clause" );
if( count == 2 ) break;
}
}
}
}
我运行的结果是:
No Exception
ThreeException
In finally clause
In finally clause
书上的结果是:
ThreeException
In finally clause
No Exception
In finally clause
PS:不管那一种结果我都看不懂 还请教
[此贴子已经被作者于2006-8-1 11:39:49编辑过]
----------------解决方案--------------------------------------------------------
我运行你的程序结果是你书上的结果啊`
----------------解决方案--------------------------------------------------------
............不是吧 那我工具有问题 那还请你讲一下 结果怎么来的啊
----------------解决方案--------------------------------------------------------
我快晕了 cmd和工具运行得出的结果不一样...........
----------------解决方案--------------------------------------------------------
大家帮你分析分析这个程序啊 我顶上来
----------------解决方案--------------------------------------------------------
class ThreeException extends Exception { }
public class FinallyWorks {
static int count = 0;
/** Creates a new instance of FinallyWorks */
public static void main( String args[] ) {
while( true ) {
try {
if( count++ == 0 )
throw new ThreeException( );
System.out.println( "No Exception" );
} catch( ThreeException e ) {
System.err.println( "ThreeException" );
} finally{
System.err.println( "In finally clause" );
if( count == 2 ) break;
}
}
}
}
至于LZ说的运行结果不对,那我就郁闷了……你是用什么工具!?我记得书上说过,如果你用非JDK工具编译运行错误,可以用JDK试下,很可能你就正确了!
呵,祝你好运!
----------------解决方案--------------------------------------------------------
我的主要问题不是这个啊 是谁可以帮你分析一下 这个结果怎么来的啊!!!
ThreeException
In finally clause
No Exception
In finally clause
[此贴子已经被作者于2006-8-3 10:35:57编辑过]
----------------解决方案--------------------------------------------------------
汗。。。我用JB9运行的结果是这样的:
ThreeException
In finally clause
In finally clause
No Exception
----------------解决方案--------------------------------------------------------
书上的运行结果是正确的:
首先是while循环,这个程序循环三次 0,1,2。2 的时候结束。
看看循环过程:
1:count = 0 看这个if( count++== 0 ) ,因为是count++ 而不是++count(同时count 变成1)。所以满足条件 ,于是执行if。接下来抛出异常throw new ThreeException( ); 那么就要转到catch语句了,于是System.err.println( "ThreeException" );那么就输出了一个ThreeException. 再向下执行finally语句。这个是无论有没有异常都执行的语句。于是有个In finally clause
2:count = 1 一样的过程 ,这个时候if( count++== 0 )不在满足条件了(同时count 变成2)。向下执行System.out.println( "No Exception" ); 于是有个No Exception:在向下执行,刚才说了finally语句无论有没有异常都执行于是在执行一次这个语句。又产生一次In finally clause。
3:count = 2 结束循环。
其结果就是:
ThreeException
In finally clause
No Exception
In finally clause
这个是我的理解不知道正不正确,还请高手批评指点。
----------------解决方案--------------------------------------------------------
ThreeException
In finally clause
No Exception
In finally clause
上面的是我在J#下运行后的结果
----------------解决方案--------------------------------------------------------