当我们有一个没有任何代码的 try 块是 finally 块时,编译器会很好地编译它。然而,这里没有 try 的目的——因为我们既没有捕获异常也没有清理 finally 块中的代码。
public int updateTable(InputVo sfVo){
//SqlSession session = ConnFactory.getSqlSession();
//InputMapper spMapper = session.getMapper(InputMapper .class);
int updRecs=0;
try {
mapper.updateData(sfVo);
updRecs=sfVo.getRecsUpdated();
return updRecs;
} finally {
//session.close();
}
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,为什么 JAVA 没有考虑对此进行编译时检查?
如果编译器在编译时本身抛出错误不会更好 - 比如“不能有一个空的 finally 块”
使用try-finally声明而不声明catch声明是合法的。
从JLS:
14.20.2. 执行 try-finally 和 try-catch-finally
A try statement with a finally block is executed by first executing the try block. Then there is a choice:
If execution of the try block completes normally, then the finally block is executed, and then there is a choice:
If the finally block completes normally, then the try statement completes normally.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.
You said :
we are neither catching a exception nor cleaning up code in finally block. If thats the case, why does JAVA has not considered a compile time check on this ?
What you write in the finally statement is of course at the hand of the developer.
Having a empty finally statement is useless but it is the same thing that having an empty if or for statement.
These are helpless but the compiler will not complain about it as it stays valid code in terms of compilation.
However, IDEs could emit warnings about it to point bad smells.
| 归档时间: |
|
| 查看次数: |
2516 次 |
| 最近记录: |