3 回答

TA貢獻1871條經驗 獲得超8個贊
聲明throws IOException
并不要求您實際拋出異常。
如果是這種情況,那么將無法編程,因為該方法的所有分支都需要拋出異常(即使在非異常情況下)。
這更像是一個擁有完整合約的問題,其中調用者可以處理可能的異常。這適用于可能被迫實際拋出異常的未來實現。
可能出于同樣的原因,允許重寫的方法省略已檢查的異常(您不會被迫拋出它)

TA貢獻1852條經驗 獲得超7個贊
Show Stopper 有一個很好的答案并引用了一個很好的帖子。這個答案試圖幫助 OP 了解什么是受檢查和未經檢查的異常。
檢查異常是在簽名中聲明的異常(無論是否拋出)。
public void doSomething() throws SomeExtremelyDevastatingEndOfTheWorldException {
// Maybe it might happen (but whoever calls this MUST acknowledge handle this case)
}
這個應用程序不會編譯,因為作者認為必須處理這種情況才能運行應用程序。
未經檢查的異常是不一定需要處理并且可以在運行時冒泡的異常。
public void doSomething() {
throws RuntimeException("not the end of the world...but we'll probably want this stacktrace and let the program run on");
}
現在,如果作者希望,任何異常都可以成為未經檢查的異常。

TA貢獻1801條經驗 獲得超8個贊
聲明 throws IOException 不需要該方法拋出異常。
它是方法簽名的一部分,也是設計軟件的一部分。考慮下面的例子。Interface 中有一種方法和它的兩種實現。無論是否拋出異常,兩個實現都應該具有相同的簽名。他們可以忽略異常條款。所以這是編譯器在編譯時無法顯示錯誤的有效原因。
Interface parent {
void method() throws Exception
}
Class Implementation1 {
void method() throws Exception {
System.out.println("Do not throws exception");
}
}
Class Implementation2 {
void method() throws Exception {
throw new Exception("Error");
}
}
添加回答
舉報