【发布时间】:2014-01-18 15:04:54
【问题描述】:
我有一个简单的疑问。在以下两个代码中,第一个 return 语句被放置在 finally 块内
public int method1(){
try{
// Some Stuff
} catch(Exception e){
e.printStackTrace();
} finally{
return 0;
}
}
在第二个return 语句中正常放置
public int method1(){
try{
// Some Stuff
} catch(Exception e){
e.printStackTrace();
} finally{
}
return 0;
}
这两者有什么区别吗?哪个可以用作更好的选择?为什么?
【问题讨论】:
-
你永远不应该在 finally 块中包含 return 语句。这可能会覆盖在 try 块中完成的事情,并可能导致非常复杂的逻辑。
-
finally 块中返回的任何内容实际上都会覆盖 try/catch 块中的任何异常或返回值。