2

While playing with exception handling in Java I noticed that no exception is thrown when some illegal runtime operation is being done in the catch block in Java.

Is that a bug in the language or am I missing something ? Could someone please look into it - as in why no exception is thrown from the catch block.

public class DivideDemo {

    @SuppressWarnings("finally")

    public static int divide(int a, int b){

    try{
       a = a/b;
    }
    catch(ArithmeticException e){
       System.out.println("Recomputing value");

       /* excepting an exception in the code below*/
       b=0;
       a = a/b;
       System.out.println(a);
    }
    finally{
      System.out.println("hi");
      return a;
    }
  }    
  public static void main(String[] args) {
     System.out.println("Dividing two nos");
     System.out.println(divide(100,0));
  }

}

sbose
  • 1,791
  • 5
  • 24
  • 46

1 Answers1

12

Is that a bug in the language or am I missing something ?

It's because you have return statement in your finally block:

finally {
  System.out.println("hi");
  return a;
}

This return statement effectively swallows exception and "overrides it" with returned value.

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Thanks @Tomasz , so technically, anything can be done inside the catch if covered by a return statement. Should that not be a defect in the language? ( just brainstorming ) – sbose Oct 16 '12 at 18:40
  • @SHOUBHIKBOSE -- It's "working as designed". It's a very bad idea to have a return statement in a finally block, but the language will let you do it. (No computer language can prevent you from doing stupid things.) – Hot Licks Oct 16 '12 at 18:42
  • Thanks .I wonder why the language allows one to do so ? [ I mean what could possibly be the reason for this design decision ] – sbose Oct 16 '12 at 18:45
  • @SHOUBHIKBOSE for example, you open a Stream in a try code section and close it in the finally (to free the resources even if there was an error in the try block, +1!), but you have a return at the end of the try block, so should the resources be kept in memory? – Luiggi Mendoza Oct 16 '12 at 19:00
  • @SHOUBHIKBOSE In competent hands it can be useful. For example, it could be a conditional return (inside `if`) that handles a specific situation where this would actually conform to a contract. On the other hand, you don't really need a decision **not** to include a special rule. The current state only shows the lack of any decision. – Marko Topolnik Oct 16 '12 at 19:18
  • 2
    If you remove @SuppressWarnings("finally"), you see Eclipse warning: "finally block does not complete normally". The right way is to avoid warning not to suppress it. – Aubin Oct 16 '12 at 19:29