springcloudlearner
springcloudlearner

Reputation: 457

Exception Handling Unreachable code

Following is my code, when I am commenting statement-2 then it complies fines but when I uncomment it gives Compile Time Error "Unreachable Code".

I understand why I am getting error after uncommenting it, but my question is even if I comment it still the bad() is unreachable as I am throwing an exception is catch then why it is not giving error for it ?

class Varr 
{
  public static void main(String[] args) throws Exception
  { 
    System.out.println("Main");
    try {
      good();
    } catch (Exception e) {
      System.out.println("Main catch");
      //**Statement 1**    
      throw new RuntimeException("RE");
    } finally {
      System.out.println("Main Finally");
      //  **Statement 2**    
      throw new RuntimeException("RE2");
    }
    bad();
  }
}

Upvotes: 5

Views: 5384

Answers (1)

davidxxx
davidxxx

Reputation: 131346

but my question is even if i comment it still the bad() is unreachable as i am throwing an exception is catch then why it is not giving error for it ?

Because the execution will not necessary enter in the catch statement.
Suppose that good() doesn't thrown any exception, so you don't enter in the catch and therefore bad() is then executed :

public static void main(String[] args) throws Exception
{   
    System.out.println("Main");
    try {
        good(); // doesn't throw an exception
    } catch (Exception e) { 
        System.out.println("Main catch");
        throw new RuntimeException("RE");
    }
    bad(); // execution goes from good() to here
}

Upvotes: 5

Related Questions