Unreachable statement java что это

от admin

How to Fix Unreachable Statement Errors in Java

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

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

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.

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.

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

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!

Why does Java have an "unreachable statement" compiler error?

I often find when debugging a program it is convenient, (although arguably bad practice) to insert a return statement inside a block of code. I might try something like this in Java .

of course, this would yield the compiler error.

I could understand why a warning might be justified as having unused code is bad practice. But I don’t understand why this needs to generate an error.

Is this just Java trying to be a Nanny, or is there a good reason to make this a compiler error?

8 Answers 8

Because unreachable code is meaningless to the compiler. Whilst making code meaningful to people is both paramount and harder than making it meaningful to a compiler, the compiler is the essential consumer of code. The designers of Java take the viewpoint that code that is not meaningful to the compiler is an error. Their stance is that if you have some unreachable code, you have made a mistake that needs to be fixed.

There is a similar question here: Unreachable code: error or warning?, in which the author says «Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario.» Obviously the language designers of Java agree.

Whether unreachable code should prevent compilation is a question on which there will never be consensus. But this is why the Java designers did it.

A number of people in comments point out that there are many classes of unreachable code Java doesn’t prevent compiling. If I understand the consequences of Gödel correctly, no compiler can possibly catch all classes of unreachable code.

Unit tests cannot catch every single bug. We don’t use this as an argument against their value. Likewise a compiler can’t catch all problematic code, but it is still valuable for it to prevent compilation of bad code when it can.

The Java language designers consider unreachable code an error. So preventing it compiling when possible is reasonable.

(Before you downvote: the question is not whether or not Java should have an unreachable statement compiler error. The question is why Java has an unreachable statement compiler error. Don’t downvote me just because you think Java made the wrong design decision.)

There is no definitive reason why unreachable statements must be not be allowed; other languages allow them without problems. For your specific need, this is the usual trick:

It looks nonsensical, anyone who reads the code will guess that it must have been done deliberately, not a careless mistake of leaving the rest of statements unreachable.

Java has a little bit support for «conditional compilation»

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as «unreachable» in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define «flag variables» such as:

and then write code such as:

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

It is Nanny. I feel .Net got this one right — it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

I only just noticed this question, and wanted to add my $.02 to this.

Читать:
Где хранятся библиотеки python

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:

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.

Unreachable statement error in Java

how to fix Unreachable statement error in Java

Java Unreachable statement is an error according to the Java Language Spec .

This error means that the control flow of your program can’t get to that statement, but you assume that they would be. The compiler analyzes the flow, and reports these statements to you as error messages. It is a reliable indicators of logical error in your program.

These statements might be unreachable mostly because of the following reasons:

  1. Return statement
  2. Infinite loop

Return statement

In the above example, the return function will terminate your method, meaning no line of code past it will be executed . If you want your print to go through, you should move it above the return statement. If you keep any statements after the return statement those statements are unreachable statements by the controller. By using return statement we are telling control should go back to its caller explicitly .

Infinite loop

java infinite loop

The compiler is giving you an Unreachable statement error because your System.out.print(«inside infinite loop»); code can never be reached with. When the compiler compiles the whole body of code and make byte code according to your code, it smarter enough to detects unreachable code and also dead code. So, immediate break in the for-loop makes unreachable other statements.

When the compiler reports an unreachable statement , it typically points you to the statement. When that happens, you can follow the flow of control from top to bottom to discover why the statement can never be reached. There are quite strict rules when statements are reachable in java. These rules are design to be easily evaluated and not to be 100% accurate. It should prevent basic programming errors. To reason about reachability in java you are restricted to these rules, common logic does not apply. So here are the rules from the Java Language Specification 14.21. Unreachable Statements.

Unreachable Statement Java Error – How to resolve it

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

  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,

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 Output

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 Output

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 Output

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 Output

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

  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.

Похожие статьи