【java】源碼詳解java異常處理

來源:互聯網
上載者:User

java異常處理,原理、理論很多很多,還是需要一點點去理解,去最佳化。這裡現貼出一下源碼,只為形象的感知java異常處理方式。

1.try catch

public class TestTryCatch {public static void Try() {int i = 1 / 0;try {} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {TestTryCatch.Try();}}

try catch是java程式員常常使用的捕獲異常方式,很簡單,不贅述了,上述程式執行結果:

Exception in thread "main" java.lang.ArithmeticException: / by zeroat com.jointsky.exception.TestTryCatch.Try(TestTryCatch.java:6)at com.jointsky.exception.TestTryCatch.main(TestTryCatch.java:15)

2.throws Exception

public class TestThrows {public static void Throws() throws Exception {try {int i = 1 / 0;} catch (Exception e) {throw new Exception("除0異常:" + e.getMessage());}}public static void main(String[] args) throws Exception {//注意:main函數若不加throws Exception 編譯不通過TestThrows.Throws();}}

這個例子主要理解一下throws和throw這兩個關鍵字的區別,執行結果:

Exception in thread "main" java.lang.Exception: 除0異常:/ by zeroat com.jointsky.exception.TestThrows.Throws(TestThrows.java:12)at com.jointsky.exception.TestThrows.main(TestThrows.java:20)

3.自寫異常類

public class DIYException {public static void TestDIY() {System.out.println("This is DIYException");}}

public class TestExtendsException extends DIYException {public static void Throws() throws Exception {try {int i = 1 / 0;} catch (Exception e) {DIYException.TestDIY();}}public static void main(String[] args) {// 注意:不加try{}catch(){} 編譯不通過try {TestExtendsException.Throws();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

異常處理也可自行編寫,上述程式執行結果:

This is DIYException

P.S.

問題總會莫名其妙的出來,很多東西,還是需要一點點的去積累。這需要一個過程,耐心點,多準備準備,等莫名其妙的問題出來的時候,就不那麼狼狽了。

dml@2012.11.6

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.