Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return statement in java exception handling [duplicate]

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;
             }
     }
  }
like image 448
sonal Avatar asked Mar 25 '13 14:03

sonal


People also ask

What is duplicate key exception?

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.

Can an exception be caught twice?

Java does not allow us to catch the exception twice, so we got compile-rime error at //1 .

Can you catch 2 exceptions in Java?

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.

How to handle multiple exception in single catch?

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.


2 Answers

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.

Note: It won't be executed only when

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.

like image 80
Parth Soni Avatar answered Sep 18 '22 17:09

Parth Soni


By design, the return in the finally block does always take precedence.

like image 40
Javier Avatar answered Sep 20 '22 17:09

Javier