Java中的异常处理

 1 class YiChang{
 2     public static void main(String[] args){
 3         A a=new A();
 4         a.show();
 5     }
 6 }
 7 
 8 class A{
 9     int[] i={1,2,3};
10     public void show(){
11         System.out.println(i[3]);
12     }
13 }

运行上面代码,会抛出这样的错误。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at A.show(YiChang.java:11)
at YiChang.main(YiChang.java:4)

除了让虚拟机为我们抛出异常外,我们也可以人为的控制异常。

我们有两种方法:throws和throw。throws是申明异常,throw是抛出问题对象,下面让我们具体看看这两种是怎么实现的。

首先我们在函数中加入throws(如下在10行函数处)

 1 class YiChang{
 2     public static void main(String[] args){
 3         A a=new A();
 4         a.show();
 5     }
 6 }
 7 
 8 class A{
 9     int[] i={1,2,3};
10     public void show()throws Exception{ 
11         System.out.println(i[3]);
12     }
13 }

此时的运行结果为

YiChang.java:4: 错误: 未报告的异常错误Exception; 必须对其进行捕获或声明以便抛出

让我们再看看throw,此时会用到try(){}catch(){}finally(){},try用来放可能发生问题的代码,catch用来捕获问题,finally用来放一定会执行的语句。

 1 class YiChang{
 2     public static void main(String[] args){
 3         A a=new A();
 4         try{
 5             a.show();
 6         }
 7         catch(Exception e){       //无处不在的多态
 8             System.out.println("wrong");
 9         }
10     }
11 }
12 
13 class A{
14     int[] i={1,2,3};
15     public void show(){
16         System.out.println(i[3]);
17     }
18 }

输出结果为wrong

此时我们就会想,能不能对程序中的错误实现认为的控制呢?这个时候就会用到了throw

class YiChang{
    public static void main(String[] args){
        A a=new A();
        try{
            a.show(3);
        }
        catch(Exception e){
            System.out.println("wrong");
            System.out.println("message"+e.getMessage());
            System.out.println("toString"+e.toString());
            e.printStackTrace();
        }
    }
}

class A{
    int[] i={1,2,3};
    public void show(int j) throws Exception{
        if(j>=3){
            throw new Exception("j beyond the length");
        }
        System.out.println(i[j]);
    }
}

此时我们需要看看e里面究竟有什么方法。这里写几个常用的方法:toString()、getMessage()、printStackTrace()。下面是运行结果

wrong
messagej beyond the length
toStringjava.lang.Exception: j beyond the length
java.lang.Exception: j beyond the length
    at A.show(YiChang.java:20)
    at YiChang.main(YiChang.java:5)
原文地址:https://www.cnblogs.com/Jc-zhu/p/4067960.html