my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why is this not a compilation error? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why is this not a compilation error?" Watch "Why is this not a compilation error?" New topic
Author

Why is this not a compilation error?

Michael Clare
Greenhorn

Joined: Apr 03, 2010
Posts: 28


This is a question I am told will show "B" and throw Exception.
But, I thought the Java compiler does not accept code with lines that will
never be reached. Meaning the Java compiler seems to complain about
"unreachable code" in some cases.

And it seems like System.out.println("A"); at line 8 will never
be reached, so I said this was a compile time error. But according to
the answers I am wrong, please help
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
Consider the following program :-



In the above code, the line "a=3" would never get executed and hence is not reachable, but compiler does not show any compile time error . I infer the following thing from it:-

I think whenever the direct result of any expression is not inferred in compile time (like method execution in above case and in yours case ) then no such compile time error is shown. But if you write "return " at line Y then compile time error is shown because of its direct characteristic.

Thanks !!!


SCJP 6.0 96%

(Connecting the Dots ....)
Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 438

this is not the case
when there is a case that some code follows after throw clause
then at compile time the compiler knows that any code cannot follow after throw clause
in your case
you are considering method
but methods are called at run time hence it does not give compiler error
following code gives the error



F:\Java\Javaranch problems>javac FinallyTest.java
FinallyTest.java:16: unreachable statement
public static void m1() throws Exception { throw new Exception(); System.out.
println("it may be unreacheable");}
^
1 error


SCJP 6 [86%] June 30th, 2010
OCPWCD [84%] March 26th, 2013
If you find any post useful, click the "plus one" sign on the right
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Remember that the compiler does not run the code; it just
translates the code. Your question is a good illustration.

Jim ... ...


BEE MBA PMP SCJP-6
 
 
subject: Why is this not a compilation error?
 
Similar Threads
Unreachable statements
No Unreachable error ?
An Exception question in Dan's mock exam
unreachable statement
Unreachable statement