1

Please take a look into the below code

try{
   return 0;
  }
finally{
   return 1;
}

The output of the program is 1.

I want to understand why the compiler is not throwing any error?

Why the java developers allowed the above possible programming?

Please help me to understand the concept and why it is handled this way by jvm.

Lathy
  • 879
  • 1
  • 8
  • 25
  • 7
    "I want to understand why the compiler is not throwing any error?" Which part of the language specification makes you think an error should be reported? – Jon Skeet Jul 28 '15 at 09:46
  • Check this [article](https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) – Panther Jul 28 '15 at 09:49
  • http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2 – Amadan Jul 28 '15 at 09:49
  • @Hacketo: I already read that post and it describes about the outcome of the program. Here my question is why java Compiler allows these kind of programming even when we know the try block code will never return. – Lathy Jul 28 '15 at 09:50
  • What do you want to understand ?? it happens as this is how finally is implemented and documented also. If you wanted to know why java developers decided so then you need to contact them. No one here will be able to help you – Panther Jul 28 '15 at 09:51
  • @JonSkeet: No part of lang spec defines about possibility of error. I was curious to know why they didn't allow the compiler to throw error. – Lathy Jul 28 '15 at 09:53
  • Just because some code makes no sense, it doesn't mean it's syntactically wrong. Maybe your IDE should give you a note about it, but nothing more. – Szabolcs Páll Jul 28 '15 at 09:53
  • "Why the java developers allowed the above possible programming?" <- probably just because they didn't think of it when they designed the language, and now it's too late to change it. – user253751 Jul 28 '15 at 09:53
  • 1
    @Lathy: In that case, I suggest if you're asking a similar question in the future, you make it specifically about the language rules and *not* the compiler behaviour. The compiler is just following the language spec. – Jon Skeet Jul 28 '15 at 09:54
  • @Lathy because it is a valid syntax. in [JSF 14.17](https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.17) it´s written, that a return statement just `attempts to transfer control`. Since the `return` statement is defined the following `It can be seen, then, that a return statement always completes abruptly.`, the next documentation will be telling you that this is some valid syntax: `Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.` – SomeJavaGuy Jul 28 '15 at 09:56

0 Answers0