Недостижимый оператор в Java
Недостижимый оператор в Java является ошибкой во время компиляции. Эта ошибка возникает, когда в вашем коде есть оператор, который не будет выполнен ни разу.
Недостижимый оператор в Java является ошибкой во время компиляции. Эта ошибка возникает, когда в вашем коде есть оператор, который не будет выполнен ни разу. Эта ошибка указывает на логический недостаток в потоке вашего кода.
Такая ошибка может возникнуть из-за бесконечного цикла или размещения кода после оператора return или break среди нескольких других причин.
Давайте рассмотрим несколько примеров недостижимых утверждений.
1. Недоступно во время цикла
Если условие цикла while таково, что оно никогда не является истинным, то код внутри цикла никогда не будет выполняться. Это делает код внутри цикла while недоступным.
Среда IDE указывает на ошибку при написании кода. Это довольно “разумно”.
При беге мы получаем:
2. Код после бесконечного цикла
Фрагмент кода сразу после бесконечного цикла никогда не будет выполнен. На самом деле, весь код после бесконечного цикла никогда не будет выполнен. Это должно побудить вас обратить внимание при написании конечного условия цикла.
3. Код после перерыва или продолжения инструкции
Оператор Break позволяет нам выйти из цикла. Оператор Continue позволяет нам пропустить текущую итерацию и перейти к следующей итерации, размещая код после того, как любой из двух операторов сделает оператор недоступным.
Как исправить ошибку недостижимого оператора?
Нет никакого конкретного способа исправить такую ошибку. Все зависит от того, насколько вы хороши как программист. Проблема заключается в потоке вашего кода.
Блок-схемы необходимы для понимания потока любого кода. Вы можете попробовать нарисовать блок-схему для проблемы, которую вы пытаетесь решить. Затем вы можете сопоставить свой код с блок-схемой или написать код с нуля, исходя из этого нового понимания проблемы.
Еще один вопрос, который может возникнуть при ошибке такого типа, заключается в том, нужны ли вам вообще утверждения, которые недоступны? Может быть, вам на самом деле не нужны заявления, в этом случае вы можете просто пойти дальше и удалить их.
Если вы все еще не можете понять это, вы всегда можете прокомментировать этот пост, и мы поможем вам разобраться в этом. Вот для чего мы здесь 🙂
Why does Java have an «unreachable statement» compiler error?
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.
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.
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.
Why do I get unreachable statement error in Java?
I’m putting together a code for a hailstone sequence I found in an online tutorial, but in doing so I ran into an unreachable statement error. I don’t know if my code is correct and I don’t want advice in correcting it if I’m wrong(regarding the hailstone sequence, I want to do that myself. ) ). I just want help in resolving the «unreachable statement» error at line 19.
7 Answers 7
This is an infinite loop:
Whatever comes after it never get executed (i.e. is unreachable).
In your first for loop:
You do not define the ending condition. e.g.
Therefore the loop never exits.
Your first infinite loop of for(int i=0;;i++) stops any other code from being reached.
There is an infinite loop @ line 7
You forgot to set an exit condition
This might create unexpected behaviour.
Your first for statement (in the 6’th line) is an infinite loop therefore it stops further code to be reached.
You have problem at line number 6 in your first for loop.
Here since your don’t have any exit conditions, code is going in the infinite loop and the loop never exits. Whatever outside the scope of this for loop will be unreachable since your first loop is never existing.
Consider adding the exit condition (such as break or return etc.) inside your for loop to prevent this behavior.
Unreachable statement in java while loop
While loking up «dead code» thread here dead code warning in eclipse
I tried the following simple java code:
which correctly throws a compile time error
I tweaked the code very slightly to this:
and it compiles just fine.
Is there a reason, why this compiles fine?
logically both should cause an infiniteloop and should both cause compile time error.
Am I doing something wrong?
6 Answers 6
logically both should cause an infiniteloop
Not quite: while(false) never enters the loop.
Is there a reason, why this compiles fine?
Why shouldn’t it compile fine? All statements are reachable, as opposed to the first example 🙂
Many programs intentionally have infinite loops. (Think of a server for instance, that should serve clients «for ever».) It wouldn’t make sense to refuse to compile infinite loops.
logically both should cause an infinite loop and should both cause compile time error.
No, only the second one should result in an infinite loop.
A while loop goes on as long as the condition is true. Since false is never true, the loop body will never be executed (which is why the x = 4; is unreachable in that case).
Note that if you do.
. it won’t compile, since the loop will go on for ever, and the last x = 4; will be unreachable.
Unreachable Statement Java Error – How to resolve it
Posted by: Shaik Ashish in Core Java December 11th, 2019 0 Views
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
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
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
6. Download the Source Code
This was an example of the error Unreachable Statement in Java.
Last updated on Jul. 23rd, 2021
