• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this not a compilation error?

 
Michael Clare
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 !!!
 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that the compiler does not run the code; it just
translates the code. Your question is a good illustration.

Jim ... ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic