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
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
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
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
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){
^
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
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].
I only just noticed this question, and wanted to add my $.02 to this.
In case of Java, this is not actually an option. The «unreachable code» error doesn’t come from the fact that JVM developers thought to protect developers from anything, or be extra vigilant, but from the requirements of the JVM specification.
Both Java compiler, and JVM, use what is called «stack maps» — a definite information about all of the items on the stack, as allocated for the current method. The type of each and every slot of the stack must be known, so that a JVM instruction doesn’t mistreat item of one type for another type. This is mostly important for preventing having a numeric value ever being used as a pointer. It’s possible, using Java assembly, to try to push/store a number, but then pop/load an object reference. However, JVM will reject this code during class validation,- that is when stack maps are being created and tested for consistency.
To verify the stack maps, the VM has to walk through all the code paths that exist in a method, and make sure that no matter which code path will ever be executed, the stack data for every instruction agrees with what any previous code has pushed/stored in the stack. So, in simple case of:
Object a;
if (something) { a = new Object(); } else { a = new String(); }
System.out.println(a);
at line 3, JVM will check that both branches of ‘if’ have only stored into a (which is just local var#0) something that is compatible with Object (since that’s how code from line 3 and on will treat local var#0).
When compiler gets to an unreachable code, it doesn’t quite know what state the stack might be at that point, so it can’t verify its state. It can’t quite compile the code anymore at that point, as it can’t keep track of local variables either, so instead of leaving this ambiguity in the class file, it produces a fatal error.
Of course a simple condition like if (1<2)
will fool it, but it’s not really fooling — it’s giving it a potential branch that can lead to the code, and at least both the compiler and the VM can determine, how the stack items can be used from there on.
P.S. I don’t know what .NET does in this case, but I believe it will fail compilation as well. This normally will not be a problem for any machine code compilers (C, C++, Obj-C, etc.)
In this post, we will look into Unreachable Statement Java Error, when does this occurs, and its resolution.
1. Introduction
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
- Infinite Loop before a line of code or statements
- 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.
- Before compiling, examine the flow of execution of your code to ensure that every statement in your code is reachable.
- Avoid using statements which are not at all required or related to your programming logic or algorithm implementation.
- Avoid statements immediately after return, break , continue.
- Do not place code after infinite loops.
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
The most common error developers face is the unreachable statement code because it is hidden and does not generate any error while executing. This part is hidden in a way, as the compiler does not visit or compile this part of the code because it is in a place that is the unreachable section for the code.
This article demonstrates the procedure to handle the unreachable statement code error in Java.
Multiple reasons may be the causes of unreachable statement code errors in Java, along with the corresponding solutions. This error is not syntax-based, it is purely a logical error or may occur due to human error in some cases. Before visiting the solutions, let us first visit the reasons which can be the cause of unreachable statement code errors:
Reason 1: Code Inserted After “break” Statement
The “break” statement is utilized along the decision-making statement and loops. It stops the execution cycle if the desired state is reached. The compiler does not reach the line that arrives next to the “break” statement in that block. The compiler stops the execution cycle and moves toward the next statement in the DOM hierarchy.
Visit the below code:
class Half {
public static void main(String[] args) {
for (int i = 0; i <= 10; ++i) {
if (i == 5) {
break;
System.out.println(i);
}
}
}
}
The above code should display values from “0” to “4”. But, with the usage of the statement after the “break” statement the unreachable statement error arises:
The output shows the occurrence of an unreachable statement error.
Solution: Try Inserting Code Above the “break” Statement
The solution is to use the statement outside the block in which the “block” statement is utilized. For instance, the above code executes accurately if the statement is placed outside of the “if” statement block as shown below:
The above snapshot from the IDE shows that now the unreachable statement code error is resolved.
Reason 2: Code Inserted After “continue” Statement
The “continue” statement is utilized when the programmer wants to skip a specific iteration to get executed by the loop. The compiler breaks the execution cycle whenever it finds the “continue” statement in the code. That is why the code executed after the “continue” statement causes an “unreachable statement code” error:
class Half {
public static void main(String[] args) {
for (int i = 0; i <= 10; ++i) {
if (i == 5) {
continue;
System.out.println(i);
}
}
}
}
The output of the above code looks like this:
The output shows that the “unreachable code error” has occurred.
Solution: Insert code Outside the “continue” Statement Block
To resolve it, simply utilize the code outside the “continue” statement block:
After changing the position, the error is resolved automatically.
Reason 3: Code Inserted After “return” Statement
This scenario is the same as above, the compiler skips the part of the code that is placed after the “return” statement. It is because the “return” statement is the end after which the compiler has nothing to perform as shown in the below snapshot:
Solution: Code Inserted After “return” Statement in the main() Method
To resolve it, enter the code after the “return” statement in the main() method:
Reason 4: Code Inserted After “throw” Statement
The line of code inserted after the “throw” statement in the “try” block leaves uncompiled by the compiler. For instance, visit the below code:
class Half {
public static void main(String[] args) //creation of main() method
{
try {
throw new Exception(«First exception»);
System.out.println(«After Throw exception»);
}
catch (Exception k) {
System.out.println(k.getMessage());
}
}
}
In the above code, display a dummy message that is written after the “throw” keyword.
After the execution of the above code:
The above snapshot shows the occurrence of an “unreachable code error” due to the use of code after the “throw” statement.
Solution: Insert Code Before “throw” Keyword
To resolve it, try to insert the date before the “throw” statement. For instance, visit the below snapshot of the error-resolved code:
The above output shows the exception has been removed and the code is now working properly.
Conclusion
The “unreachable statement code” error arises when the line of code is written at a place that is unreachable by the compiler. The possible places are “after the block statement”, “after the continue statement”, “after the return statement” or “below the throw statement”, etc. This is a logical error and can be easily resolved by reviewing the code multiple times and understanding the way the compiler compiles the code.
About the author
I’m a versatile technical author who thrives on adaptive problem-solving. I have a talent for breaking down complex concepts into understandable terms and enjoy sharing my knowledge and experience with readers of all levels. I’m always eager to help others expand their understanding of technology.
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"
);
}
}
}
}
- 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
Last Updated :
22 Oct, 2020
Like Article
Save Article