Error unreachable statement java

The “Unreachable Statement” error in Java arises when the compiler detects a statement that's never executable in the program's control flow.

Introduction to Statements and Compile-time Errors in Java

Statements are foundational language constructs that have an effect on the execution of a program. Statements are similar to sentences in natural languages. In Java, there are three main types of statements, namely expression statements, declaration statements, and control-flow statements [1].

As a compiled programming language, Java has an inbuilt mechanism for preventing many source code errors from winding up in executable programs and surfacing in production environments [2]. One such error, related to statements, is the unreachable statement error.

What Causes the Unreachable Statement Error?

By performing semantic data flow analysis, the Java compiler checks that every statement is reachable and makes sure that there exists an execution path from the beginning of a constructor, method, instance initializer, or static initializer that contains the statement, to the statement itself. If it finds a statement for which there is no such path, the compiler raises the unreachable statement error [3].

Unreachable Statement Error Examples

After a branching control-flow statement

The break, continue, and return branching statements allow the flow of execution to jump to a different part of the program. The break statement allows breaking out of a loop, the continue statement skips the current iteration of a loop, and the return statement exits a method and returns the execution flow to where the method was invoked [4]. Any statement that follows immediately after a branching statement is, by default, unreachable.

After break

When the code in Fig. 1(a) is compiled, line 12 raises an unreachable statement error because the break statement exits the for loop and the successive statement cannot be executed. To address this issue, the control flow needs to be restructured and the unreachable statement removed, or moved outside the enclosing block, as shown in Fig. 1(b).

(a)

package rollbar;

public class UnreachableStatementBreak {
   public static void main(String... args) {
       int[] arrayOfInts = {35, 78, 3, 589, 12, 1024, 135};

       int searchFor = 12;

       for (int integer : arrayOfInts) {
           if (integer == searchFor) {
               break;
               System.out.println("Found " + searchFor);
           }
       }
   }
}
UnreachableStatementBreak.java:12: error: unreachable statement
        System.out.println("Found " + searchFor);
        ^

(b)

package rollbar;

public class UnreachableStatementBreak {
   public static void main(String... args) {
       int[] arrayOfInts = {35, 78, 3, 589, 12, 1024, 135};

       int searchFor = 12;
       boolean found = false;

       for (int integer : arrayOfInts) {
           if (integer == searchFor) {
               found = true;
               break;               
           }
       }

       if (found) {
           System.out.println("Found " + searchFor);
       }
   }
}
Found 12
Figure 1: Unreachable statement after a break statement (a) error and (b) resolution

After continue

Just as with the break statement, any statement following a continue statement will result in an unreachable statement error. The continue statement on line 12 in Fig. 2(a) halts the current iteration of the for loop and forwards the flow of execution to the subsequent iteration, making the print statement unreachable. Placing the print statement in front of the continue statement resolves the issue (Fig. 2(b)).

(a)

package rollbar;

public class UnreachableStatementContinue {
   public static void main(String... args) {
       int[] arrayOfInts = {35, 78, 3, 589, 12, 1024, 135};

       int oddSum = 0;

       for (int integer : arrayOfInts) {
           if (integer % 2 == 0) {
               continue;
               System.out.println("Skipping " + integer + " because it's even");
           }
           oddSum += integer;
       }
       System.out.println("nThe sum of the odd numbers in the array is: " + oddSum);
   }
}
UnreachableStatementContinue.java:12: error: unreachable statement
        System.out.println("Skipping " + integer + " because it's even");
        ^

(b)

package rollbar;

public class UnreachableStatementContinue {
   public static void main(String... args) {
       int[] arrayOfInts = {35, 78, 3, 589, 12, 1024, 135};

       int oddSum = 0;

       for (int integer : arrayOfInts) {
           if (integer % 2 == 0) {
               System.out.println("Skipping " + integer + " because it's even");
               continue;
           }
           oddSum += integer;
       }
       System.out.println("nThe sum of the odd numbers in the array is: " + oddSum);
   }
}
Skipping 78 because it's even
Skipping 12 because it's even
Skipping 1024 because it's even

The sum of the odd numbers in the array is: 762
Figure 2: Unreachable statement after a continue statement (a) error and (b) resolution

After return

The return statement on line 10 in Fig. 3 unconditionally exits the factorial method. Therefore, any statement within this method that comes after the return statement cannot be executed, resulting in an error message.

(a)

package rollbar;

public class UnreachableStatementReturn {

   static int factorial(int n) {
       int f = 1;
       for (int i = 1; i <= n; i++) {
           f *= i;
       }
       return f;
       System.out.println("Factorial of " + n + " is " + f);
   }

   public static void main(String... args) {
       factorial(10);
   }
}
UnreachableStatementReturn.java:11: error: unreachable statement
        System.out.println("Factorial of " + n + " is " + f);
        ^

(b)

package rollbar;

public class UnreachableStatementReturn {

   static int factorial(int n) {
       int f = 1;
       for (int i = 1; i <= n; i++) {
           f *= i;
       }
       return f;
   }

   public static void main(String... args) {
       int n = 10;
       System.out.println("Factorial of " + n + " is " + factorial(n));
   }
}
Factorial of 10 is 3628800
Figure 3: Unreachable statement after a return statement (a) error and (b) resolution

After a throw statement

An exception is an event that occurs during the execution of a program and disrupts the normal flow of instructions. For an exception to be caught, it has to be thrown by some code, which can be any code, including code from an imported package, etc. An exception is always thrown with the throw statement [5].

Any statement added to a block after throwing an exception is unreachable and will trigger the unreachable statement error. This happens because the exception event forces the execution to jump to the code catching the exception, usually a catch clause within a try-catch block in the same or a different method in the call stack. See Fig. 4 for an example.

(a)

package rollbar;

public class UnreachableStatementException {
   public static void main(String... args) {
       try {
           throw new Exception("Custom exception");
           System.out.println("An exception was thrown");
       } catch (Exception e) {
           System.out.println(e.getMessage() + " was caught");
       }
   }
}
UnreachableStatementException.java:7: error: unreachable statement
        System.out.println("An exception was thrown");
        ^

(b)

package rollbar;

public class UnreachableStatementException {
   public static void main(String... args) {
       try {
           throw new Exception("Custom exception");
       } catch (Exception e) {
           System.out.println("An exception was thrown");
           System.out.println(e.getMessage() + " was caught");
       }
   }
}
An exception was thrown
Custom exception was caught
Figure 4: Unreachable statement after a throw statement (a) error and (b) resolution

Inside a while loop with invariably false condition

The while statement continually executes (loops through) a code block while a particular condition evaluates to true. If this condition can’t be met prior to entering the while loop, the statement(s) inside the loop will never be executed. This will cause the compiler to invoke the unreachable statement error (Fig. 5).

package rollbar;

public class UnreachableStatementWhile {
   public static void main(String... args) {
       final boolean start = false;

       while (start) {
           System.out.println("Unreachable Statement");
       }
   }
}
UnreachableStatementWhile.java:7: error: unreachable statement
        while (start){
                     ^
Figure 5: Unreachable while statement

Summary

This article helps understand, identify, and resolve the unreachable statement error, which is a frequently encountered compile-time semantic error in Java. This error stems from irregularities in the execution flow of a program, where certain statements are unreachable by any means, i.e., none of the possible execution paths lead to them. To avoid this error, careful design and examination of the execution flow of a program is advisable.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Oracle, 2021. Expressions, Statements, and Blocks (The Java™ Tutorials > Learning the Java Language > Language Basics). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html . [Accessed Nov. 10, 2021].

[2] Rollbar, 2021. Illegal Start of Expression: A Java Compile-time Errors Primer. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-illegal-start-of-expression-in-java/. [Accessed Nov. 10, 2021].

[3] Oracle, 2021. The Java® Language Specification. Chapter 14. Blocks, Statements, and Patterns. Unreachable Statements. Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.22. [Accessed Nov. 10, 2021].

[4] Oracle, 2021. Branching Statements (The Java™ Tutorials > Learning the Java Language > Language Basics). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html. [Accessed Nov. 10, 2021].

[5] Oracle, 2021. How to Throw Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html. [Accessed Nov. 10, 2021].

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    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:

    • Have a return statement before them 
    • Have an infinite loop before them 
    • Any statements after throwing exception in a try block 

    Scenarios where this error can occur: 

    • Have a return statement before them: When a return statement gets executed, then that function execution gets stopped right there. Therefore any statement after that wont get executed. This results in unreachable code error.

    Example: 

    Java

    class GFG {

        public static void main(String args[])

        {

            System.out.println("I will get printed");

            return;

            System.out.println("I want to get printed");

        }

    }

    • Compile Errors: 

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

    1 error 

    • Have an infinite loop before them: Suppose inside “if” statement if you write statements after break statement, then the statements which are written below “break” keyword will never execute because if the condition is false, then the loop will never execute. And if the condition is true, then due to “break” it will never execute, since “break” takes the flow of execution outside the “if” statement.

    Example: 

    Java

    class GFG {

        public static void main(String args[])

        {

            int a = 2;

            for (;;) {

                if (a == 2)

                {

                    break;

                    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 
     

    • Any statement after throwing an exception: If we add any statements in a try-catch block after throwing an exception, those statements are unreachable because there is an exceptional event and execution jumps to catch block or finally block. The lines immediately after the throw is not executed.

    Example: 

    Java

    class GFG {

        public static void main(String args[])

        {

            try {

                throw new Exception("Custom Exception");

                System.out.println("Hello");

            }

            catch (Exception exception) {

                exception.printStackTrace();

            }

        }

    }

    • Compile Errors: 

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

    1 error 
     

    • Any statement after writing continue : If we add any statements in a loop after writing the continue keyword, those statements are unreachable because execution jumps to the top of the for loop. The lines immediately after the continue is not executed.
      Example: 
       

    Java

    class GFG {

        public static void main(String args[])

        {

            for (int i = 0; i < 5; i++)

            {

                continue;

                System.out.println("Hello");

            }

        }

    }

    • Compile Errors: 

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

    1 error 

    In this post, we will look into Unreachable Statement Java Error, when does this occurs, and its resolution.

    1. Introduction

    Unreachable Statement Java

    An unreachable Statement is an error raised as part of compilation when the Java compiler detects code that is never executed as part of the execution of the program. Such code is obsolete, unnecessary and therefore it should be avoided by the developer. This code is also referred to as Dead Code, which means this code is of no use.

    2. Explanation

    Now that we have seen what actually is Unreachable Statement Error is about, let us discuss this error in detail about its occurrence in code with few examples.

    Unreachable Statement Error occurs in the following cases

    1. Infinite Loop before a line of code or statements
    2. Statements after return, break or continue

    2.1 Infinite Loop before a line of code or statements

    In this scenario, a line of code is placed after an infinite loop. As the statement is placed right after the loop, this statement is never executed as the statements in the loop get executed repeatedly and the flow of execution is never terminated from the loop. Consider the following code,

    Example 1

    public class JavaCodeGeeks
    {
    	public static void main(String[] args) {
    		while(true)
    		{
    			System.out.println("Hi");
    		}
    		System.out.println("Hello");
    	}
    }

    Output

    JavaCodeGeeks.java:8: error: unreachable statement
                    System.out.println("Hello");

    In this example, compiler raises unreachable statement error at line 8 when we compile the program using javac command. As there is an infinite while loop before the print statement of “hello”, this statement never gets executed at runtime. If a statement is never executed, the compiler detects it and raises an error so as to avoid such statements.

    Now, let us see one more example which involves final variables in the code.Example 2

    public class JavaCodeGeeks
    {
    	public static void main(String[] args) {
    		final int a=10;
    		final int b=20;
    		while(a>b)
    		{
    			System.out.println("Inside while block");
    		}
    		System.out.println("Outside while block");
    	}
    }

    Output

    JavaCodeGeeks.java:7: error: unreachable statement
                    {
                    ^
    1 error

    In the above example, variables a and b are final. Final variables and its values are recognized by the compiler during compilation phase. The compiler is able to evaluate the condition a>b to false. Hence, the body of the while loop is never executed and only the statement after the while loop gets executed. While we compile the code, the error is thrown at line 7 indicating the body of the loop is unreachable.

    Note: if a and b are non-final, then the compiler will not raise any error as non-final variables are recognized only at runtime.

    2.2 Statements after return, break or continue

    In Java language, keywords like return, break, continue are called Transfer Statements. They alter the flow of execution of a program and if any statement is placed right after it, there is a chance of code being unreachable. Let us see this with an example, with the return statement.Example 3

    public class JavaCodeGeeks
    {
    	public static void main(String[] args) {
    		System.out.println(foo(40));
    
    	}
    	public static int foo(int a)
    	{
    		return 10;
    		System.out.println("Inside foo()");
    	}
    }

    Output

    JavaCodeGeeks.java:10: error: unreachable statement
                    System.out.println("Inside foo()");
                    ^
    JavaCodeGeeks.java:11: error: missing return statement
            }
            ^
    2 errors

    In this example, when foo() method is called, it returns value 10 to the main method. The flow of execution inside foo() method is ended after returning the value. When we compile this code, error is thrown at line 10 as print statement written after return becomes unreachable.

    Let us look into the second example with a break statement.Example 4

    public class JavaCodeGeeks
    {
    	public static void main(String[] args) {
    	  for(int i=1;i<5;i++)
    	  {
    	  	System.out.println(i);
    	  	break;
    	  	System.out.println("After break");
    	  }
    	}
    } 

    Output

    JavaCodeGeeks.java:8: error: unreachable statement
                    System.out.println("After break");
                    ^
    1 error 

    When the above code is compiled, the compiler throws an error at line 8, as the flow of execution comes out of for loop after break statement, and the print statement which is placed after break never get executed.

    Finally, let us get into our final example with a continued statement.Example 5

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

    Output

    JavaCodeGeeks.java:10: error: unreachable statement
                                    System.out.println("After continue");

    When the above code is compiled, the compiler throws an error at line 10. At runtime as part of program execution, when the value increments to 5 if block is executed. Once the flow of execution encounters continue statement in if block, immediately the flow of execution reaches the start of for loop thereby making the print statement after continue to be unreachable.

    3. Resolution

    Keep these points in your mind so that you avoid this error while compilation of your code.

    1. Before compiling, examine the flow of execution of your code to ensure that every statement in your code is reachable.
    2. Avoid using statements which are not at all required or related to your programming logic or algorithm implementation.
    3. Avoid statements immediately after return, break , continue.
    4. Do not place code after infinite loops.

    4. Unreachable Statement Java Error – Summary

    In this post, we have learned about the Unreachable Statement Error in Java. We checked the reasons for this error through some examples and we have understood how to resolve it. You can learn more about it through Oracle’s page.

    5. More articles

    • java.lang.StackOverflowError – How to solve StackOverflowError
    • java.lang.ClassNotFoundException – How to solve Class Not Found Exception (with video)
    • java.lang.NullPointerException Example – How to handle Java Null Pointer Exception (with video)
    • Try Catch Java Example
    • For Each Loop Java 8 Example
    • Simple while loop Java Example (with video)
    • For loop Java Example (with video)
    • Online Java Compiler – What options are there
    • What is null in Java

    6. Download the Source Code

    This was an example of the error Unreachable Statement in Java.

    Last updated on Jul. 23rd, 2021

    1. Cause of the unreachable statement Error in Java
    2. Solve the unreachable statement Error in Java

    Solve the Unreachable Statement Error in Java

    This tutorial demonstrates the unreachable statement error in Java.

    Cause of the unreachable statement Error in Java

    The unreachable statement error occurs when we try to put a statement after branching control flow statements. The branching statements include break, continue, and return which are used to jump to a different part of code.

    These statements are usually included in the loop to break it, skip an iteration, or return a value. When we put a code statement immediately after these branching statements, it will throw the compilation error unreachable statement.

    Here are examples of the error unreachable statement using the break, continue, and return statements:

    Using break:

    package delftstack;
    
    public class Unreachable_Statement {
        public static void main(String... args) {
            int[] DemoArray = {350, 780, 300, 500, 120, 1024, 1350};
    
            int DemoNumber = 1024;
    
            for (int INTEGER : DemoArray) {
                if (INTEGER == DemoNumber) {
                    break;
                    System.out.println("The number is: " + DemoNumber);
                }
            }
        }
    }
    

    The output for this is:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        Unreachable code
    
        at delftstack.Unreachable_Statement.main(Unreachable_Statement.java:12)
    

    Using continue:

    package delftstack;
    
    public class Unreachable_Statement {
        public static void main(String... args) {
            int[] DemoArray = {350, 780, 300, 500, 120, 1024, 1350};
    
            int DemoNumber = 1024;
    
            for (int INTEGER : DemoArray) {
                if (INTEGER == DemoNumber) {
                    continue;
                    System.out.println("The number is: " + DemoNumber);
                }
            }
        }
    }
    

    The output for this will also be the same:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        Unreachable code
    
        at delftstack.Unreachable_Statement.main(Unreachable_Statement.java:12)
    

    Using return:

    package delftstack;
    
    public class Unreachable_Statement {
        public static void main(String... args) {
            int[] DemoArray = {350, 780, 300, 500, 120, 1024, 1350};
    
            int DemoNumber = 1024;
    
            for (int INTEGER : DemoArray) {
                if (INTEGER == DemoNumber) {
                    return;
                    System.out.println("The number is: " + DemoNumber);
                }
            }
        }
    }
    

    The output is:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        Unreachable code
    
        at delftstack.Unreachable_Statement.main(Unreachable_Statement.java:12)
    

    Solve the unreachable statement Error in Java

    The solution is to avoid writing any code immediately after the branching statements. See the code solution for the error raised using the break statement:

    package delftstack;
    
    public class Unreachable_Statement {
        public static void main(String... args) {
            int[] DemoArray = {350, 780, 300, 500, 120, 1024, 1350};
    
            int DemoNumber = 500;
            boolean FoundNumber = false;
            for (int INTEGER : DemoArray) {
                if (INTEGER == DemoNumber) {
                    FoundNumber = true;
                    break;
                }
            }
            if (FoundNumber) {
                System.out.println("The number is: " + DemoNumber);
            }
        }
    }
    

    We have put the statement in another if condition. The code will now work properly.

    See output:

    Similarly, we can create a solution for continue and return statements. The rule is not to put any code immediately after the branching statements.

    Понравилась статья? Поделить с друзьями:
  • Error unpacking of archive failed cpio bad magic
  • Error unnecessary else after return no else return
  • Error unmounting dev sda1 target is busy udisks error quark 14
  • Error unmounting dev nvme0n1p3
  • Error unmarshalling return nested exception is