If execution doesn't cause exception then control goes to finally block. So is the return statement in try block is being ignored by JVM? . Or if exception occurs then control goes to catch block there also it ignored return statment and control go to finally block and return from finally
public class Helper {
public int showException(int a, int b){
try{
int c=a/b;
return c;
} catch(Exception e){
return 0;
} finally{
return 3;
}
}
}
The DuplicateKeyException exception is thrown if an entity EJB object or EJB local object cannot be created because an object with the same key already exists. This exception is thrown by the create methods defined in an entity bean's home or local home interface.
Java does not allow us to catch the exception twice, so we got compile-rime error at //1 .
Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.
Because finally
block will be executed every time whether you enter in try
or in catch
, I think that's why its called finally :)
FROM JAVA DOCS
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
By design, the return in the finally
block does always take precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With