Open In App

Unreachable Code Error in Java

The Unreachable statements refers to statements that won’t get executed during the execution of the program are called Unreachable Statements. These statements might be unreachable because of the following reasons:

Scenarios where this error can occur: 



Example: 




class GFG {
    public static void main(String args[])
    {
 
        System.out.println("I will get printed");
 
        return;
 
        // it will never run and gives error
        // as unreachable code.
        System.out.println("I want to get printed");
    }
}

prog.java:11: error: unreachable statement 
System.out.println(“I want to get printed”); 

1 error 



Example: 




class GFG {
    public static void main(String args[])
    {
        int a = 2;
        for (;;) {
 
            if (a == 2)
            {
                break;
                // it will never execute, so
                // same error will be there.
                System.out.println("I want to get printed");
            }
        }
    }
}

  1. Compile Errors: 

prog.java:13: error: unreachable statement 
System.out.println(“I want to get printed”); 

1 error 
 

Example: 




class GFG {
    public static void main(String args[])
    {
 
        try {
            throw new Exception("Custom Exception");
            // Unreachable code
            System.out.println("Hello");
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

prog.java:7: error: unreachable statement 
System.out.println(“Hello”); 

1 error 
 




class GFG {
    public static void main(String args[])
    {
        for (int i = 0; i < 5; i++)
        {
            continue;
            System.out.println("Hello");
        }
    }
}

prog.java:6: error: unreachable statement 
System.out.println(“Hello”); 

1 error 


Article Tags :