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 zero
- at 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 zero
- at 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 block
- e.printStackTrace();
- }
- }
- }
異常處理也可自行編寫,上述程序執行結果:
This is DIYException
P.S.
問題總會莫名其妙的出來,很多東西,還是需要一點點的去積累。這需要一個過程,耐心點,多准備准備,等莫名其妙的問題出來的時候,就不那麼狼狽了。
[email protected]