目录
结论
程序执行到return时
- 如果返回的是基础变量,如Int,String等,返回值,即最终返回。
- 如果返回的是复合变量,如Map,自定义类型,返回引用[地址],return之后仍然会被改变。
finally的功能是处理一些善后工作,比如关闭IO,清楚缓存等。
通常不使用finally做赋值操作,容易引起混乱,如果finally里有return会执行。
基础类型Int,返回值
@Slf4j
public class FinallyandReturn {
public static void main(String[] args) {
log.info(""+finallyAndReturn());
}
public static int finallyAndReturn() {
int a = 10;
try {
a = 20;
a = a/0;
return a;
}catch(Exception e) {
a = 30;
return a;
}finally {
log.info("I'm running finally");
a = 40;
}
}
}
结果:30
基础类型String,返回值
@Slf4j
public class FinallyandReturn {
public static void main(String[] args) {
log.info(finallyAndReturn().toString());
}
public static String finallyAndReturn() {
String str = "10";
Map map = new HashMap();
try {
str = "20";
str = ""+ 10/0;
return str;
}catch(Exception e) {
str = "30";
return str;
}finally {
log.info("I'm running finally");
str = "40";
}
}
}
结果:30
基础类型StringBuffer,返回值
@Slf4j
public class FinallyandReturn {
public static void main(String[] args) {
log.info(finallyAndReturn().toString());
}
public static String finallyAndReturn() {
StringBuffer sb = new StringBuffer();
sb.append("10");
Map map = new HashMap();
try {
sb.delete(0, sb.length()).append("20");
sb.append(""+ 10/0);
return sb.toString();
}catch(Exception e) {
sb.delete(0, sb.length()).append("30");
return sb.toString();
}finally {
log.info("I'm running finally");
sb.delete(0, sb.length()).append("40");
}
}
}
结果:30
复合类型Map,返回引用
@Slf4j
public class FinallyandReturn {
public static void main(String[] args) {
log.info(finallyAndReturn().toString());
}
public static Map finallyAndReturn() {
int a = 10;
Map map = new HashMap();
try {
a = 20;
a = a/0;
map.put("a",a);
return map;
}catch(Exception e) {
a = 30;
map.put("a",a);
return map;
}finally {
log.info("I'm running finally");
a = 40;
map.put("a",a);
}
}
}
结果: {a = 40}
自定义类型,返回引用
@Slf4j
public class FinallyandReturn {
public static void main(String[] args) {
log.info(finallyAndReturn().name);
}
public static Data finallyAndReturn() {
Data data = new Data();
data.setName("10");;
try {
data.setName("20");
data.setName(""+ 10/0);
return data;
}catch(Exception e) {
data.setName("30");
return data;
}finally {
log.info("I'm running finally");
data.setName("40");
}
}
static class Data{
String name;
void setName(String name){
this.name = name;
}
}
}
结果:name=40
执行了finally 里的return
@Slf4j
public class FinallyandReturn {
public static void main(String[] args) {
log.info(finallyAndReturn().toString());
}
public static Map finallyAndReturn() {
int a = 10;
Map map = new HashMap();
try {
a = 20;
a = a/0;
map.put("a",a);
return map;
}catch(Exception e) {
a = 30;
map.put("a",a);
return map;
}finally {
log.info("I'm running finally");
a = 40;
map.put("a",a);
return new HashMap();
}
}
}
结果:{}