Java基础系列
- Java的hashcode与equals方法
- Java类初始化顺序
- ThreadPoolExecutor线程池如何弹性伸缩
- HashMap的几个要点
- Integer的缓存
- 什么场景下使用阻塞队列
- volatile的使用及DCL模式
- try-catch-finally中的return
序
本文主要简述try-catch-finally中有return的情况。笔试面试经常考到。
题目
/**
* http://qing0991.blog.51cto.com/1640542/1387200
* Created by codecraft on 2016-03-08.
*/
public class ReturnDemo {
/**
* try有return,finally也有return,以finally的为准
* @return
*/
public static int noException(){
int i=10;
try{
System.out.println("i in try block is:"+i); //10
i--; //9
return --i; //8
}
catch(Exception e){
--i;
System.out.println("i in catch - form try block is:"+i);
return --i;
}
finally{
System.out.println("i in finally - from try or catch block is:"+i); //8
return ++i; //9 返回这个
}
}
public static int tryCatchReturn(){
int i=10;
try{
System.out.println("i in try block is:"+i); //10
return --i; //9
}
catch(Exception e){
--i;
System.out.println("i in catch - form try block is:"+i);
return --i;
}
finally{
System.out.println("i in finally - from try or catch block is:"+i); //9
--i; //8
System.out.println("i in finally block is:"+i); //8
}
}
/**
* finally的return的优先级最高
* 但try/catch的return也会执行
* @return
*/
public static int tryCatchFinallyReturn(){
int i=10;
try{
System.out.println("i in try block is:"+i); //10
i = i/0;
return --i;
}
catch(Exception e){
System.out.println("i in catch - form try block is:"+i); //10
--i; //9
System.out.println("i in catch block is:"+i); //9
return --i; //8
}
finally{
System.out.println("i in finally - from try or catch block is--"+i); //8
--i; //7
System.out.println("i in finally block is--"+i); //7
return --i; //6
}
}
public static int tryExCatchReturn(){
int i=10;
try{
System.out.println("i in try block is:"+i); //10
i=i/0;
return --i;
}catch(Exception e){
System.out.println("i in catch - form try block is:"+i); //10
return --i; //9 返回这个
}finally{
System.out.println("i in finally - from try or catch block is:"+i); //9
--i; //8
System.out.println("i in finally block is:"+i); //8
}
}
public static int tryExCatchExReturn() {
int i = 10;
try {
System.out.println("i in try block is:" + i); //10
i = i / 0;
return --i;
} catch (Exception e) {
System.out.println("i in catch - form try block is:" + i); //10
int j = i / 0;
return --i;
} finally {
System.out.println("i in finally - from try or catch block is:" + i); //10
--i; //9
--i; //8
System.out.println("i in finally block is:" + i); //8
return --i; //7 返回这个
}
}
public static void main(String[] args){
System.out.println("###" + noException()); //9
System.out.println("###" + tryCatchReturn()); //7
System.out.println("###" + tryCatchFinallyReturn()); //6
System.out.println("###" + tryExCatchReturn()); //9
System.out.println("###" + tryExCatchExReturn()); //7
}
}
小结
如果finally中有return,则最后的返回以它为准,同时try或catch的return如果可以运行到,也会执行其表达式。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。