1 使用规则
如果finally块中有return语句,则try或catch中的return语句被忽略。
finally块中应该避免使用return语句,因为finally块中如果使用return语句,会显示的消化掉try、catch块中的异常信息,屏蔽了错误的发生。
如果仅try/catch语句有return语句,则返回try/catch中变量此时对应的值,此后对变量做任何的修改,都不影响try中return的返回值。
尽量在try/catch中使用return语句,通过finally块中达到对try或者catch返回值修改是不可行的。
如果finally块中抛出异常,则整个try、catch、finally块中抛出异常。
finally块中避免再次抛出异常,否则整个包含try语句块的方法回抛出异常,并且会消化掉try、catch块中的异常。
2 代码示例
public class Demo1 {
public static void main(String[] args) {
System.out.println(fun1());// try
System.out.println(fun2());// catch
System.out.println(fun3());// finally
System.out.println(fun4());// finally
}
// 仅try有return语句,返回try中元素值
public static String fun1() {
String str = null;
try {
str = "try";
return str;
} catch (Exception e){
str = "catch";
return str;
} finally {
str = "finally";
}
}
// 仅catch有return语句,返回catch中元素值
public static String fun2() {
String str = null;
try {
str = "try";
throw new Exception();
} catch (Exception e){
str = "catch";
return str;
} finally {
str = "finally";
}
}
// finally中有return,try/catch中的return被忽略
@SuppressWarnings("finally")
public static String fun3() {
String str = null;
try {
str = "try";
return str;
} catch (Exception e) {
str = "catch";
return str;
} finally {
str = "finally";
return str;
}
}
@SuppressWarnings("finally")
public static String fun4() {
String str = null;
try {
str = "try";
throw new Exception();
} catch (Exception e) {
str = "catch";
return str;
} finally {
str = "finally";
return str;
}
}
}