This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception vs return Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception vs return" Watch "Exception vs return" New topic
Author

Exception vs return

Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
Code :
=================================================
class Test
{
public static void main(String[] args)
{
int j = 1;
try
{
int i = doIt() / (j = 2);
} catch (Exception e)
{
System.out.println(" j = " + j);
}
}
public static int doIt() throws Exception {
throw new Exception("FORGET IT");//1
}
}
=================================================
Why this code compiles successfully, without return statement inside doIt() method? If remove //1, then you'll get error message "missing return statement".... :roll:
Rajinder Yadav
Ranch Hand

Joined: Jan 18, 2002
Posts: 178
I tried this out and your are correct!
I am guessing here that the Java compiler is smart enough to see that in the doIt() method, the control flow never gets past the throw statement, so it doesn't care about the return value (because it would never be reached anyways).
This may be more of an issue with the sourcecode parser then the java language? Anyone got an idea on this one??


<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
hi Rajindar,
u were right. compiler is SMART. if u try to write something after the throws in the doIt() method it will give u an error saying that statement is not reachable!
regards
maulin.
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
Gentlemen,
where can I read about this rule?
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
JLS 14.20 Unreachable Statements
HIH


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
Thanx
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception vs return