[java]源码详解java异常处理


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


1.try catch

[java]
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程序员常常使用的捕获异常方式,很简单,不赘述了,上述程序执行结果:
[plain] 
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
[java]
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这两个关键字的区别,执行结果:
[plain] 
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.自写异常类
[java]
public class DIYException { 
 
    public static void TestDIY() { 
 
        System.out.println("This is DIYException"); 
    } 

[java]
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(); 
        } 
    } 

异常处理也可自行编写,上述程序执行结果:
[plain]
This is DIYException 

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


 

相关内容

    暂无相关文章

评论关闭