Ошибка unreachable statement
Прохожу урок на StartAndroid, возникла ошибка в коде, не могу понять как исправить, нужный класс импортирован, всё переписал как в примере, помогите разобраться. Ошибка unreachable statement на строке:
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) item.getMenuInfo();
public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks < private static final int CM_DELETE_ID = 1; ListView lvData; DB db; SimpleCursorAdapter simpleCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = new DB(this); db.open(); String[] from = new String[]; int[] to = new int[]; simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0); lvData = (ListView) findViewById(R.id.lvData); lvData.setAdapter(simpleCursorAdapter); registerForContextMenu(lvData); getSupportLoaderManager().initLoader(0, null, this); > public void onButtonClick(View view) < db.addRec("sometext " + (simpleCursorAdapter.getCount() + 1), R.drawable.alligator); getSupportLoaderManager().getLoader(0).forceLoad(); >@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) < super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CM_DELETE_ID, 0, R.string.delete_record); >@Override public boolean onContextItemSelected(MenuItem item) < return super.onContextItemSelected(item); if (item.getItemId() == CM_DELETE_ID) < AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) item.getMenuInfo(); db.delRec(acmi.id); getSupportLoaderManager().getLoader(0).forceLoad(); return true; >return super.onContextItemSelected(item); > @Override protected void onDestroy() < super.onDestroy(); db.close(); >@Override public Loader onCreateLoader(int id, Bundle args) < return new MyCursorLoader(this, db); >@Override public void onLoadFinished(Loader loader, Cursor data) < simpleCursorAdapter.swapCursor(data); >@Override public void onLoaderReset(Loader loader) < >static class MyCursorLoader extends CursorLoader < DB db; public MyCursorLoader(Context context, DB db) < super(context); this.db = db; >@Override public Cursor loadInBackground() < Cursor cursor = db.getAllData(); try < Thread.sleep(18000); >catch (InterruptedException e) < e.printStackTrace(); >return cursor; > > >
Unreachable statement error in Java
The «Unreachable Statement» error indicates that certain statements in your program cannot be executed because the control flow does not reach them, despite your assumption that they would be executed. The compiler analyzes the flow of the program and identifies these statements as unreachable, providing error messages to indicate potential logical errors in the code. Addressing these errors is crucial to ensure the correct execution of the program and to avoid unintended behaviors or program crashes.
Java Unreachable statement is an error according to the Java Language Spec .
These statements might be unreachable mostly because of the following reasons:
- Return statement
- Infinite loop
Return statement
public bool myMessage() < return true; /* The implementation goes here */ >
In the given example, the return statement will terminate the method, causing any code lines after it to be skipped and remain unexecuted. To ensure the print statement is executed, it should be placed above the return statement within the method. Any statements placed after the return statement become unreachable, as the method has already been exited. The return statement explicitly instructs the program to return control to the calling method and is used to convey a value back to the caller if needed. Careful placement of return statements is essential to maintain the intended control flow and ensure the proper functioning of the program.
Infinite loop

The «Unreachable statement» error occurs because the compiler analyzes the code and identifies certain statements as unreachable. In this case, the statement System.out.print(«inside infinite loop»); can never be reached because of the immediate break statement inside the for-loop. The compiler is smart enough to detect such cases of unreachable code, and it raises an error to prevent the generation of bytecode for code that will never be executed. By using a break statement in this scenario, the for-loop is exited prematurely, and any subsequent statements in the loop body are deemed unreachable by the compiler. Properly managing control flow and avoiding unreachable code is crucial to ensure the code’s correctness and optimize program performance.
When the compiler reports an unreachable statement, it usually provides information about the specific statement that is unreachable in the code. By following the flow of control from the top of the code to the bottom, developers can analyze and identify why that particular statement can never be reached during program execution.
Conclusion
The rules for determining reachability in Java, as defined in the Java Language Specification 14.21. section 14.21, are designed to be straightforward and easy to evaluate, rather than being 100% accurate. These rules are in place to prevent common programming errors and guide developers in writing valid and logically consistent code. When reasoning about reachability in Java, one must adhere to these defined rules, as common logic may not always apply in certain situations. Abiding by these reachability rules ensures code correctness, improves code readability, and enhances the overall reliability of Java programs.
- Reached end of file while parsing
- Int Cannot Be Dereferenced Error — Java
- How to fix java.lang.classcastexception
- How to fix java.util.NoSuchElementException
- How to fix «illegal start of expression» error
- How to resolve java.net.SocketException: Connection reset
- Non-static variable cannot be referenced from a static context
- Error: Could not find or load main class in Java
- How to Handle OutOfMemoryError in Java
- How to resolve java.net.SocketTimeoutException
- How to handle the ArithmeticException in Java?
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).
package rollbar; public class UnreachableStatementBreak < public static void main(String. args) < int[] arrayOfInts = ; 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); ^
package rollbar; public class UnreachableStatementBreak < public static void main(String. args) < int[] arrayOfInts = ; 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
- Docs Overview
- Setting up Rollbar
- Notifications
- Deploy Tracking
- Telemetry
- Security & Compliance
- API
почему Unreachable statement
Может кто знает почему у меня int z = 5 подчеркнуто красным с коментарием Unreachable statement ?
public static void main(String[] args) throws IOException while(true) int x = System.in.read(); System.out.println(x); > int z = 5; System.out.println(z); >
Комментарии (2)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Уровень 18
18 апреля 2021, 08:28
У Вас, в строке 3, начинается бесконечный цикл, без возможности выхода. Поэтому все операции после него, недостижимы. Недостижимых операций в Java быть не должно — компилятор не пропустит.
Уровень 24
18 апреля 2021, 11:47
Точно! Я так зациклился на второй части кода, что совсем забыл про цикл. Спасибо!
- Курсы программирования
- Регистрация
- Курс Java
- Помощь по задачам
- Цены
- Задачи-игры
Сообщество
JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.