File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

Why is this not a compilation error?

Michael Clare
Ranch Hand

Joined: Apr 03, 2010
Posts: 31

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: 446

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 unreachable statement
public static void m1() throws Exception { throw new Exception(); System.out.
println("it may be unreacheable");}
1 error

SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
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 ... ...

I agree. Here's the link:
subject: Why is this not a compilation error?
It's not a secret anymore!