码迷,mamicode.com
首页 > 编程语言 > 详细

java中的异常(一)

时间:2017-11-13 20:03:36      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:nbsp   输出   code   ati   color   dex   错误   pre   except   

java异常的概念

执行期的错误(javac xxx.java)

运行期的错误(java xxx)

 

这里讲的是运行期出现的错误

class TestEx {
    public static void main(String[] args)
    {
     try{
        int[] arr={1,2,3};
        System.out.print(1);
        System.out.println(arr[4]);
        System.out.print(2);
    }    catch(ArrayIndexOutOfBoundsException ae){
        System.out.print(3);
        ae.printStackTrace();
    }
    }
}

上面这段代码的输出结果是3

为啥12没打印出来呢?System.out.println(arr[4])这段带代码想获取数组中的第五个元素但是没有所以报错了直接执行了catch中的代码块。也就是说一旦出错try中的代码就不会执行而是会执行接收这个错误的catch代码块中的代码。

catch(ArrayIndexOutOfBoundsException ae)

这段代码可以理解为声明一个ArrayIndexOutOfBoundsException类型的ae变量作为catch方法的形参

在出错时java解释器会调用catch方法并且new出一个新的ArrayIndexOutOfBoundsException类型的实例然后传给ae

 

java中的异常(一)

标签:nbsp   输出   code   ati   color   dex   错误   pre   except   

原文地址:http://www.cnblogs.com/lishihai/p/7827571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!