今天在写代码涉及到try-catch-finally中,io流需要关闭,在finally里面进行处理。那我的返回值放在哪里呢? try里面还是 try外面
这里写了一个demo,供参考使用:
public class Test {
public static void main(String[] args) throws Exception {
Test t = new Test();
// System.out.println(t.t1());
// System.out.println(t.t2());
System.out.println(t.t3());
}
public String t1() throws Exception{
try{
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("222");
}
Thread.sleep(1000);
System.out.println("111");
return "1";
}
public String t2() throws Exception{
try{
System.out.println("333");
return "2";
}catch(Exception e){
e.printStackTrace();
}finally{
//在 return "2" 之前执行
Thread.sleep(1000);
System.out.println("222");
}
System.out.println("111");
return "1";
}
public String t3() throws Exception{
try{
System.out.println("333");
return "2";
}catch(Exception e){
e.printStackTrace();
}finally{
//在 return "2" 之前执行
System.out.println("222");
return "3";
}
}
//这是我写 导入Excel 实现
public String t4() throws Exception{
try{
return "2";
}catch(Exception e){
e.printStackTrace();
}finally{
//在 return "2" 之前执行
System.out.println("222");
}
}
}
依次将,首先看 t1方法打印:
public String t1() throws Exception{
try{
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("222");
}
Thread.sleep(1000);
System.out.println("111");
return "1";
}
先打印finally里面的代码,再打印try-catch-finally 之后的代码,返回值为1
看t2方法打印如下:
public String t2() throws Exception{
try{
System.out.println("333");
return "2";
}catch(Exception e){
e.printStackTrace();
}finally{
//在 return "2" 之前执行
Thread.sleep(1000);
System.out.println("222");
}
System.out.println("111");
return "1";
}
结果的返回值为2 说明是在try里面返回的,说明 return "1" 不会走了,这里还是按照代码的顺序来执行的,但是 finally里面的语句是在 打印333之后执行的,也就说明finally的代码是在return返回之前执行 ,说明 finally是在return之前执行的(return一定在try里面).
那么这样看的话t3方法 打印就好解释了:
public String t3() throws Exception{
try{
System.out.println("333");
return "2";
}catch(Exception e){
e.printStackTrace();
}finally{
//在 return "2" 之前执行
System.out.println("222");
return "3";
}
}
finally里面有返回值,但finally是在return之前执行,那么 finally 就直接返回。
t4方法不能运行:这就是我之前犯的问题,在try里面返回 finally 控制流关闭 外面还是要有一个return值。为什么要有值呢?
如果try里面的代码抛出异常了,就不会走 try里面的return "2" 了 所以要在外面加一个 return
public String t4() throws Exception{
try{
int c = 1/0; //这里抛出异常了 后面果断不执行了呗s
return "2";
}catch(Exception e){
e.printStackTrace();
}finally{
//在 return "2" 之前执行
System.out.println("222");
}
return null;
}
综上,try里面存在异常的可能情况 会走 catch 那么可以在catch里面return ,否则在try里面return 即可
如下:
public String t4() throws Exception{
try{
int c = 1/0;
return "2";
}catch(Exception e){
System.out.println("333");
return "111";
}finally{
//在 return "2" 之前执行
System.out.println("222");
}
}
先打印333 再打印222 最后打印111.