源码详解Java异常处理
源码详解Java异常处理
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.
问题总会莫名其妙的出来,很多东西,还是需要一点点的去积累。这需要一个过程,耐心点,多准备准备,等莫名其妙的问题出来的时候,就不那么狼狈了。
dml@2012.11.6
评论暂时关闭