java的錯誤和異常的區別

來源:互聯網
上載者:User

1)  error都是繼承自父類java.lang.Error,而exception都繼承自java.lang.Exception.

2)  再看看JDK中對於java.lang.Error和java.lang.Exception的解釋。

    java.lang.Error: An Error is a subclass of
Throwable that indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions.
即:Error是Throwable的子類,用於標記嚴重錯誤。合理的應用程式不應該去try/catch這種錯誤。絕大多數的錯誤都是非正常的,就根本不該出現的。
欠款

    java.lang.Exception: The class Exception and
its subclasses are a form of Throwable that indicates conditions that a
reasonable application might want to catch. 即Exception
是Throwable的一種形式的子類,用於指示一種合理的程式想去catch的條件。即它僅僅是一種程式運行條件,而非嚴重錯誤,並且鼓勵使用者程式去catch它。

3)  Error和RuntimeException 及其子類都是未檢查的異常(unchecked exceptions),而所有其他的Exception類都是檢查了的異常(checked exceptions).
軟體開發
checked exceptions: 通常是從一個可以恢複的程式中拋出來的,並且最好能夠從這種異常中使用程式恢複。比如FileNotFoundException, ParseException等。

unchecked exceptions: 通常是如果一切正常的話本不該發生的異常,但是的確發生了。比
如ArrayIndexOutOfBoundException,
ClassCastException等。從語言本身的角度講,程式不該去catch這類異常,雖然能夠從諸如RuntimeException這樣的異
常中catch並恢複,但是並不鼓勵終端程式員這麼做,因為完全沒要必要。因為這類錯誤本身就是bug,應該被修複,出現此類錯誤時程式就應該立即停止執
行。

因此,面對Errors和unchecked exceptions應該讓程式自動終止執行,程式員不該做諸如try/catch這樣的事情,而是應該查明原因,修改代碼邏輯。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.