Unreachable statement là câu lệnh không bao giờ được thực thi do luồng điều khiển không thể đến đó. Compiler Java phát hiện và báo lỗi compile-time error cho unreachable code.
Ví dụ gốc: Vòng lặp vô tận với biến non-final
class DemoExample {
int a = 2, b = 3;
void displayMsg() {
while (a < b) { // a=2, b=3 → luôn true
System.out.println("The first variable is less than the second");
}
System.out.println("This is an unreachable statement"); // COMPILE ERROR
}
}
public class Demo {
public static void main(String[] args) {
DemoExample instance = new DemoExample();
instance.displayMsg();
}
}
Kết quả Compile
Demo.java:7: error: unreachable statement
System.out.println("This is an unreachable statement");
^
1 error
Tại sao compiler bắt lỗi?
- Biến
avàblà instance fields non-final. - Compiler không phân tích giá trị runtime của non-final fields (có thể bị thay đổi bởi thread khác, reflection, subclass...).
- Tuy nhiên, trong cùng một method, compiler thấy
avàbkhông bị gán lại (no assignment) → suy luậna < bluôn true → vòng lặp vô tận → code sau unreachable. - Đây là flow analysis của compiler (Java Language Specification §14.21).
So sánh với biến final
class FinalExample {
final int a = 2, b = 3; // FINAL
void funcSample() {
while (a < b) { // Compile-time constant expression
System.out.println("First less than second");
}
System.out.println("Unreachable"); // COMPILE ERROR (cũng báo)
}
}
Cả hai đều báo unreachable. Sự khác biệt: với final, compiler dùng constant folding (biết giá trị compile-time). Với non-final, compiler dùng flow analysis trong method.
Các trường hợp Unreachable Statement thường gặp
| Trường hợp | Ví dụ |
|---|---|
Code sau return | return; System.out.println("unreachable"); |
Code sau throw | throw new RuntimeException(); log(); |
Code sau continue/break trong loop | while(true) { break; System.out.println("unreachable"); } |
Vòng lặp vô tận while(true) hoặc for(;;) không có break/return | Code sau loop |
if (false) { ... } (constant condition) | Block else hoặc code sau if |
try { return; } finally { } code sau try-catch | Finally chạy, nhưng code sau try-catch unreachable nếu try luôn return/throw |
Cách khắc phục
- Thêm điều kiện thoát:
while (a < b && !shouldStop). - Dùng
break,return,throwtrong loop. - Nếu logic đúng là infinite loop (server loop), đặt code sau trong thread riêng hoặc trước loop.
- Đừng.comment out code – xóa hẳn hoặc dùng version control.
Lưu ý: Unreachable != Dead Code
- Unreachable statement: Compile-time error (Java spec bắt buộc).
- Dead code: Code có thể reach nhưng không bao giờ execute ở runtime (ví dụ:
if (false) { ... }với config flag). Compiler có thể optimize away (DCE - Dead Code Elimination) nhưng không báo lỗi.