• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unreachable code ?

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code:

public class exception {
public static void main(String args[]) {
System.out.println("A");
try {
return;
}
catch(Exception e) {
System.out.println("B");
return;
}
System.out.println("C");
}
}

When I tried to compile this, I got:
exception.java:11: unreachable statement
System.out.println("C");
^
1 error


Now, consider the following code:
public class exception1{
public static void main(String args[]){
System.out.println("A");
try {
return;
}
catch(Exception e) {
System.out.println("B");
}
System.out.println("C");
}
}

O/p: A

How is it that the first program results in a compile-time error, while the second one compiles and runs without any errors? The only difference between the 2 programs is that the first program has a return statement in the catch block, which I guess, is inconsequential. In both cases, the statement System.out.println("C") is outside the try-catch block.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in fact the return statement in the catchblock is crucial.
Think the logic through and you'll find out why: the return statement in the catch block combined with the return statement in the try block means that any code after the catch block (which after all catches everything) can no longer be reached.
 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In both cases, there is a return statement in the try block. So, I guess the catch block itself is never executed. Then, how does the catch block come into the picture? Plz guide.
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kedar

Yes in your program probably the catch block would never get executed but still the compiler doesn't know that this block of code would not give any error.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kedar, there are buttons underneath the Add Reply Button. One o those buttons says "CODE". You can use this button to post code into your post and the code will keep its indentations, which makes the code more readible.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic