Reputation: 2718
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in 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();
}
}
If thats the case, why does JAVA has not considered a compile time check on this ?
Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"
Upvotes: 2
Views: 4426
Reputation: 14572
To add some context, finally is just keyword/label to identify a block statement linked to the try
. It's like a goto
that is called in the try
.
Every block statement can be empty.
if(true){}
--
while(true){}
--
public void method(){}
even this is valid
public void method(){
{}
}
So, we could say that the compiler don't care about the content of those, only the syntax in it.
Upvotes: 2
Reputation: 1656
Since you surrounded your exception-throwing code in a try-catch
or try-finally
statement, the compiler knows you processed the potential error. What you do with it is up to you, it is authorized to ignore it.
You could argue: "How is that different than no try at all?". The difference is that if you don't put it in a try
clause, the compiler can't know if you did it on purpose or you forgot it.
Basically, catching an exception is mandatory, but processing it isn't.
Upvotes: 0
Reputation: 131356
Using a try-finally
statement without declaring a catch
statement is legal.
From the 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.
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.
Upvotes: 6