Win a copy of Machine Learning with R: Expert techniques for predictive modeling this week in the Artificial Intelligence and Machine Learning forum!
  • 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

exception and the return value of a method

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?
Posts: 24654
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.
I'm a lumberjack and I'm okay, I sleep all night and work all day. Lumberjack ad:
Java file APIs (DOC, XLS, PDF, and many more)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!