源码详解Java异常处理


Java异常处理,原理、理论很多很多,还是需要一点点去理解,去优化。这里现贴出一下源码,只为形象的感知Java异常处理方式。

1.try catch

  1. public class TestTryCatch { 
  2.  
  3.     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.  
  3.     public static void Throws() throws Exception { 
  4.         try { 
  5.  
  6.             int i = 1 / 0
  7.  
  8.         } catch (Exception e) { 
  9.  
  10.             throw new Exception("除0异常:" + e.getMessage()); 
  11.  
  12.         } 
  13.  
  14.     } 
  15.  
  16.     public static void main(String[] args) throws Exception { 
  17.         //注意:main函数若不加throws Exception 编译不通过  
  18.         TestThrows.Throws(); 
  19.     } 

这个例子主要理解一下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.  
  3.     public static void TestDIY() { 
  4.  
  5.         System.out.println("This is DIYException"); 
  6.     } 
  1. public class TestExtendsException extends DIYException { 
  2.     public static void Throws() throws Exception { 
  3.         try { 
  4.  
  5.             int i = 1 / 0
  6.  
  7.         } catch (Exception e) { 
  8.  
  9.             DIYException.TestDIY(); 
  10.         } 
  11.  
  12.     } 
  13.  
  14.     public static void main(String[] args) { 
  15.         // 注意:不加try{}catch(){} 编译不通过  
  16.         try { 
  17.             TestExtendsException.Throws(); 
  18.         } catch (Exception e) { 
  19.             // TODO Auto-generated catch block  
  20.             e.printStackTrace(); 
  21.         } 
  22.     } 

异常处理也可自行编写,上述程序执行结果:

This is DIYException 

P.S.

问题总会莫名其妙的出来,很多东西,还是需要一点点的去积累。这需要一个过程,耐心点,多准备准备,等莫名其妙的问题出来的时候,就不那么狼狈了。

dml@2012.11.6

相关内容