• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception vs return

 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gentlemen,
where can I read about this rule?
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS 14.20 Unreachable Statements
HIH
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic