import java.io.*; import java.util.*; public class test1 {
public static int test(){ try{ String line; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; line = in.readLine() ; int i = Integer.parseInt(line.trim()) ; return i ; finally{//编译时这里出错 System.out.print("wrong!"); } }catch (IOException e){ System.out.println(e); return -1; } }
import java.util.*;
public class test1 {
public static int test(){
try{
String line;
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in)) ;
line = in.readLine() ;
int i = Integer.parseInt(line.trim()) ;
return i ;
finally{//编译时这里出错
System.out.print("wrong!");
}
}catch (IOException e){
System.out.println(e);
return -1;
}
}
public static void main(String[] args){
test();
}
} ///:~
应该是return后面的语句是不会执行的
finally块是不能放在try块里的,语法错误!
那么
try
{
System.out.print("111");
return;
}
catch(Exception e){}
finally
{}
时finally会不会执行呢?答案是肯定的!
那么有人说了finally是不是什么时候都被执行呢?答案是否定的!
只有1种情况下finally块不会被执行,就是在try块中调用System.exit(0)方法的时候!
这里如果没人去过怎么会告诉你啊!
找google吧!我认为finally应该会执行的,记得以前有个一个帖子,建议楼主搜索一下以前的帖子!
public class Test {
Test(){
try{
System.out.println("try.");
return;
finally{
System.out.print("finally in try.");
}}catch (Exception e){
System.out.println(e);
}finally{
System.out.println("finally.");
}
}
public static void main(String[] args){
Test t = new Test();
}
}
编译后(我用的是J2SDK 1.42)
>javac Test.java
Test.java:7: 'finally' without 'try'
finally{
^
1 error
以上错误信息是不是说明finally必须和try成对出现?
为了证实这个想法我改了代码
代码2 Test2.java
public class Test2 {
Test2(){
try{
System.out.println("try.");
return;
try{
System.out.println("try in try.");
}catch(Exception e){}
finally{
System.out.println("finally in try.");
}}catch (Exception e){
System.out.println(e);
}finally{
System.out.println("finally.");
}
}
public static void main(String[] args){
Test2 t = new Test2();
}
}
编译后
>javac Test2.java
Test2.java:7: unreachable statement
try{
^
1 error
是说(内部的)try语句无法到达?
我把return语句去掉后
编译运行正常小弟只是个初学者,代码写的可能有些幼稚,但我至少证实了自己的想法.当然有可能我是错的,可能我还没想到其他的情况,或者我还没学到其他的可能性.所以希望各位有耐心的前辈能给些指点