Try catch in java
If I have the following code:
try {
Entity questionEntity = datastore.get(currentKey);
questionEntity.doSomething();
} catch (EntityNotFoundException e) {
Entity questionEntity = new Entity(currentKey);
}
Where the datastore.get()
function throws an exception, will the following 开发者_如何学运维lines of code (questionEntity.doSomething();
) in the try block be executed?
No, questionEntity.doSomething();
will won't be executed if datastore.get(currentKey);
throws an exception and this is trivially easy to verify and would have probably taken you less time to try it out yourself rather than posting a question on SO.
No, if get
throws an exception, control will transfer either to the catch block shown (if the exception is an EntityNotFoundException
) or higher up the stack otherwise. It won't just continue onto the next line.
Part of the point of exceptions is to avoid the code continuing to try to work as if nothing has happened when something has gone wrong. This avoids you (say) overwriting good data with corrupt or incomplete data if the data fetching failed.
No:
- If EntityNotFoundException, the catch will be executed
If any other Exception, the exception will be thrown up to calling code.
Consider a finally clause if code MUST be executed. (In this case, that wouldn't work, because this is the only place the entity is initialized
No it will not. The code will continue to the catch block immediately after the exception. Skipping all code after the exception.
No - it will jump immediately to:
Entity questionEntity = new Entity(currentKey);
...in your catch{} block.
精彩评论