• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

exception and the return value of a method

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a little surprised why Java allows this. See the following code snippet



This method compiles fine. So this method promised to return an int value, but it will never do because of the exception thrown. It is impossible to add more code after the throw statement, since that would be unreachable. At the same time, a return before the throw statement would cause the throw statement unreachable. I understand that if we put the throw statement inside a if statement and check some conditions, we can return an int and not always throw the exception.

I am surprised that the compiler didn't ask me to change the int to a void. So the compiler will not check the return type if the method can be determined at compile time to end abruptly?
 
Marshal
Posts: 24594
55
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

That method promises to either return an int value or throw an Exception. (But not both, obviously.) So it would be quite wrong for the compiler to complain about the absence of a return statement, since throwing Exception is part of the method's specification.

Normally the compiler doesn't do a lot of examining the code to see what it does, but this is one place where it does examine the code. In particular it looks at every possible path of execution, through all of the if-else statements and switch-case statements and all that. For this particular method, every possible path of execution must either return an int value or throw an Exception for the method to be accepted by the compiler. And as you can see, that rule is satisfied by the code you posted.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!