Java 中的不可達語句
1. 概述
在本教程中,我們將討論Java 規範,該規範規定,如果任何語句無法訪問,編譯器應引發錯誤。不可達語句是程式執行過程中永遠無法執行的程式碼,因為程式流程無法到達它。我們將看到與此定義相對應的各種程式碼範例。
2.循環中break
指令後的程式碼
在循環中,如果我們將指令放在break
語句之後,它們將無法存取:
public class UnreachableStatement {
public static void main(String[] args) {
for (int i=0; i<10; i++) {
break;
int j = 0;
}
}
}
讓我們嘗試使用javac
編譯我們的程式碼:
$ javac UnreachableStatement.java
UnreachableStatement.java:9: error: unreachable statement
int j = 0;
^
1 error
如所料,編譯失敗,因為int j = 0;
聲明無法存取。同樣,循環中的continue
關鍵字後面的指令也是無法存取的:
public static void main(String[] args) {
int i = 0;
while (i<5) {
i++;
continue;
int j = 0;
}
}
3. 一段while(true)
while(true)
指令意味著其中的程式碼永遠運行。因此,之後的任何程式碼都無法存取:
public static void main(String[] args) {
while (true) {}
int j = 0;
}
再聲明int j = 0;
在前面的程式碼中無法存取。此註解對於使用do-while
結構的等效程式碼也有效:
public static void main(String[] args) {
do {} while (true);
int j = 0;
}
另一方面, while(false)
循環內的任何程式碼都是不可存取的:
public static void main(String[] args) {
while (false) {
int j = 0;
}
}
4. 方法返回後的程式碼
方法在return
語句後立即退出。因此,該指令之後的任何程式碼都無法存取:
public static void main(String[] args) {
return;
int i = 0;
}
再一次, int j = 0;
無法存取該行,從而引發編譯器錯誤。同樣,當throw
語句未包含在try-catch
區塊內或未在throws
子句中指定時,該方法將異常完成。因此,此行之後的任何程式碼都無法存取:
public static void main(String[] args) throws Exception {
throw new Exception();
int i = 0;
}
回顧一下,如果所有程式碼分支都返回,則無論如何都無法存取以下程式碼:
public static void main(String[] args) throws Exception {
int i = new Random().nextInt(0, 10);
if (i > 5) {
return;
} else {
throw new Exception();
}
int j = 0;
}
在此程式碼中,我們選擇了0
(含)和10
(不含)之間的隨機數。如果這個數字大於5
,我們立即返回,否則,我們拋出一個通用Exception
。因此, if-else
區塊之後的程式碼沒有可能的執行路徑。
5. 死但可存取的程式碼
最後,讓我們注意到,從編譯器的角度來看,即使是明顯的死程式碼也不是強制不可存取的。特別是,它不會評估if
語句內的條件:
public static void main(String[] args) {
if (false) {
return;
}
}
即使我們乍看之下就知道if
區塊內的程式碼是死程式碼,該程式碼也能成功編譯。
六,結論
在本文中,我們研究了許多無法存取的語句。開發人員社群中存在關於無法存取的程式碼是否應該引發警告或錯誤的爭論。 Java 語言遵循的原則是每個編寫的程式碼都應該有一個目的,因此會引發錯誤。在 C++ 等其他語言中,由於編譯器可以執行程式碼,儘管程式碼不連貫,因此它只會發出警告。