gpt4 book ai didi

java - try block 与空 finally block

转载 作者:行者123 更新时间:2023-11-29 06:52:09 25 4
gpt4 key购买 nike

当我们有一个没有任何代码的 try block 是 finally block 时,编译器可以很好地编译它。但是,这里没有尝试的目的 - 因为我们既没有捕获异常也没有清理 finally block 中的代码。

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();
}
}

如果是这样,为什么 JAVA 没有考虑对此进行编译时检查?

如果编译器本身在编译时抛出错误——比如“不能有一个空的 finally block ”,那就更好了

最佳答案

使用 try-finally 语句而不声明 catch 语句是合法的。

来自JLS :

14.20.2. Execution of try-finally and 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.

你说:

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 ?

你在finally语句中写什么当然是在开发者的手中。
有一个空的 finally 语句是没有用的,但是它有一个空的 iffor 语句是一样的。
这些都是无奈的,但编译器不会提示它,因为它在编译方面保持有效代码。
但是,IDE 可能会发出有关它的警告以指出难闻的气味。

关于java - try block 与空 finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44385491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com