Blog |

How to Fix Unreachable Statement Errors in Java

How to Fix Unreachable Statement Errors in Java
Table of Contents

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].

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape