| Author |
unreachable code?
|
jon ruane
Greenhorn
Joined: Mar 08, 2007
Posts: 13
|
|
can someone please explain why the System.out statement at line //1 didnt throw an 'unreachable code error'. i felt for sure that it would, as the call above it redirects it to another method. are 'unreachable code' errors usually found in loops? thank you. public class MyProgram { public static void throwIt() { throw new RuntimeException(); } public static void main(String[] args) { try { System.out.println("hello world"); throwIt(); System.out.println("done with block"); //1 } catch (RuntimeException e) { System.out.println("catch"); } finally { System.out.println("finally"); } } }
|
 |
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
|
|
Hi Jon, Output: hello world catch finally
You code compiles and runs fine. You did convert a line 1, you should have written instead of a method call that throws the RuntimeException. Then only you are right that "next line of code is not reachable" Regards, cmbhatt [ April 11, 2007: Message edited by: Chandra Bhatt ]
|
cmbhatt
|
 |
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
|
|
|
The compiler doesn't go as far as looking into the throwIt() method and determining that it always throws.
|
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
The 'unreachable code' error has its limits. The compiler checks for some cases of unreachable code, but it will not go and trace into the throwIt() method to see if there's something there that might make some code in main() unreachable. If the compiler would have to check all possible kinds of unreachable code, the compiler would have to be incredibly complicated - it would have to trace all kinds of strange code paths. What if your code looked like this: Would you expect the compiler to check if method2 never returns normally, and to do that it have to check method1, etc. What if method1 was in a different class or somewhere else, probably in a JAR file in a third-party library? Would the compiler have to examine the compiled classes in that library to check if your println line was unreachable? You can make up other arbitrarily complex examples: [ April 11, 2007: Message edited by: Jesper Young ]
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
|
|
Thanks Jesper Young, By the way I clicked to this link; I got quite nicely given explanation. What are limitations of the compiler while recognizing the non-reachable code. It can only recognize like: Can you count more cases? please give here!!! Thanks, cmbhatt
|
 |
 |
|
|
subject: unreachable code?
|
|
|