标签:
如果Try和Catch中存在return语句的时候Finally内的语句是否会执行,执行的时候对结果又有什么影响呢?我写了个例子来试验这个问题:
public static Map<String, String> getMapTry() { Map<String, String> map = new HashMap<String, String>(); map.put("KEY", "INIT"); try { map.put("KEY", "TRY"); return map; } catch (Exception e) { map.put("KEY", "CATCH"); e.printStackTrace(); } finally { map.put("KEY", "FINALLY"); } System.out.println("---------end--------"); return map; } public static Map<String, String> getMapCatch() { Map<String, String> map = null; try { map.put("KEY", "TRY"); } catch (Exception e) { map = new HashMap<>(); map.put("KEY", "CATCH"); e.printStackTrace(); return map; } finally { map.put("KEY", "FINALLY"); } System.out.println("---------end--------"); return map; } public static int getInt() { Map<String, String> map = null; int ret =0; try { map.put("KEY", "TRY"); ret = 1; } catch (Exception e) { map = new HashMap<>(); map.put("KEY", "CATCH"); e.printStackTrace(); return ret; } finally { map.put("KEY", "FINALLY"); ret =3; } System.out.println("---------end--------"); return ret; } public static void main(String[] args) { System.out.println("try:" + getMapTry().get("KEY").toString()); System.out.println("catch:" + getMapCatch().get("KEY").toString()); System.out.println("int:" + getInt()); }
执行结果:
try:FINALLY
java.lang.NullPointerException
at com.wmshua.test.FinallyReturnRelation.getMapCatch(FinallyReturnRelation.java:43)
at com.wmshua.test.FinallyReturnRelation.main(FinallyReturnRelation.java:14)
catch:FINALLY
java.lang.NullPointerException
at com.wmshua.test.FinallyReturnRelation.getInt(FinallyReturnRelation.java:63)
at com.wmshua.test.FinallyReturnRelation.main(FinallyReturnRelation.java:15)
int:0
结果分析:
引用类型发生了变化,基本数据类型没有修改。
从执行结果得出以下结论:
标签:
原文地址:http://www.cnblogs.com/inbase/p/4560616.html