歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 源碼詳解Java異常處理

源碼詳解Java異常處理

日期:2017/3/1 10:07:43   编辑:Linux編程

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

1.try catch

  1. public class TestTryCatch {
  2. 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程序員常常使用的捕獲異常方式,很簡單,不贅述了,上述程序執行結果:

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

2.throws Exception

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

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

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

3.自寫異常類

  1. public class DIYException {
  2. public static void TestDIY() {
  3. System.out.println("This is DIYException");
  4. }
  5. }
  1. public class TestExtendsException extends DIYException {
  2. public static void Throws() throws Exception {
  3. try {
  4. int i = 1 / 0;
  5. } catch (Exception e) {
  6. DIYException.TestDIY();
  7. }
  8. }
  9. public static void main(String[] args) {
  10. // 注意:不加try{}catch(){} 編譯不通過
  11. try {
  12. TestExtendsException.Throws();
  13. } catch (Exception e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. }
  17. }
  18. }

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

This is DIYException

P.S.

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

[email protected]

Copyright © Linux教程網 All Rights Reserved