不对,你试试这个程序: package test;import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { System.out.println(tcf()); }
public static int tcf(){ try{ System.out.println("try"); throw new Exception(); //return i = one(); } catch (Exception e) { System.out.println("catch"); return one(); } finally{ System.out.println("finally"); return two(); } } public static int one(){ System.out.println("one"); return 1; }
public static int two(){ System.out.println("two"); return 2; }}输出是: try catch one finally two 2说明是先执行catch中的return one()中的one()方法, 但不return, 执行完再执行finally
http://www.laozizhu.com/view.jsp?articleId=28
/**
* return和finally的执行顺序分析.
*
* @author 老紫竹研究室(laozizhu.com)
*
*/
public class Test {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
int b = 0;
try {
return b = 4 + 2; // #1
} finally {
System.out.println(b); // #2
}
}
}
这个程序执行的是test 返回的是int 这个和后面的finally没有关系啊
打印的是6 和后面有什么关系吗
会做finally,finally不管前面有没有捕捉到都会执行.
记住finally是永远都执行的.
这 不合理啊。。
望达人指定!
try{
//会出现异常的地方
}catch(SomeException e) {
//出现异常如何处理的地方
}finally{
//不管是否出现异常都要处理的情况,比如关闭数据库联系,关闭打开的文件等等
}
try{
//会出现异常的地方
}catch(SomeException e) {
//出现异常如何处理的地方
}finally{
//不管是否出现异常都要处理的情况,即使已经有return语句比如关闭数据库联系,关闭打开的文件等等
}
//即使已经有return语句也会执行finally
public static void main(String[] args) {
System.out.println(frequenceCheck());
} @SuppressWarnings("finally")
public static int frequenceCheck() {
try{
System.out.println("in try block");
return 1;
}catch(Exception e){
System.out.println("in catch block");
return 2;
}finally{
System.out.println("in finally block");
return 3;
}
}输出是3
前面的代码 -> try -> finally -> 后面的代码2.如果有异常,没有return
前面的代码 -> try(直到发生错误的前一行) -> catch -> finally -> 后面的代码3.如果没有异常,有return
前面的代码 -> try(return前一行) -> finally -> return语句
System.out.println("in try block");
---return 1 并没有return 而是执行finally
如果finally 下没有return 的话,输出的就是1
除非有
System.exit(0);
退出就不执行了啊
不对,你试试这个程序:
package test;import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
System.out.println(tcf());
}
public static int tcf(){
try{
System.out.println("try");
throw new Exception();
//return i = one();
}
catch (Exception e) {
System.out.println("catch");
return one();
}
finally{
System.out.println("finally");
return two();
}
} public static int one(){
System.out.println("one");
return 1;
}
public static int two(){
System.out.println("two");
return 2;
}}输出是:
try
catch
one
finally
two
2说明是先执行catch中的return one()中的one()方法, 但不return, 执行完再执行finally
的确,应该是TRY->CATCH->FINALLY 该执行的语句都执行,包括RETURN,每一次RETURN的返回值其实都被保存了起来,无论返回值在哪里被改写,或者被改写了多少次,最后都只是把预先保存好的返回值返回,而不是FINALLY完之后又跳到TRY的RUTURN去执行。