215 异常处理之try...catch

215 异常处理之try...catch

【异常处理】

> 为什么要处理异常?系统默认的处理异常的方法会停止程序运行,但实际应用过程中,我们不希望程序停止运行。因此我们人为处理异常。

自己处理异常的两种方案

1.try…catch

2.throws

【try…catch】

格式:

try{

可能出现异常的代码

}catch(异常类名 变量名or对象名){

异常的处理代码

}

//异常类名 == ArrayIndexOutOfBoundsException

//执行流程:

//程序从try里面的代码开始执行,如果出现异常,会自动生成一个异常类对象,

//这个异常对象将被提交给Java运行的系统,到catch中找匹配的异常类,找到后处理异常。

//执行完毕后,程序继续往下执行

【思路】

写一个3个元素的数组,让控制台输出[3],制造索引越界的问题

--------------------------------------------------------------

(module)myException

(package)it03e215

class)ExceptionDemo

--------------------------------------------------------------

package it03e215;

public class ExceptionDemo {

    public static void main(String[] args) {

        System.out.println("215/begin");

        method();

        System.out.println("end");

    }

    public static void method(){

        try{

            int[] arr = {1,2,3};

            System.out.println("215/arr[3]:"+arr[3]);

        }catch(ArrayIndexOutOfBoundsException e){//what is e?

            //System.out.println("ArrayIndexOutOfBoundsException");

            //OUTPUT:

//        215/begin

//        ArrayIndexOutOfBoundsException

//        end

            e.printStackTrace();

            //OUTPUT:

//        215/begin

//        end

//        e.printStackTrace() gives no tips but keep JVM working till end

        }

    }

}

猜你喜欢

转载自blog.csdn.net/m0_63673788/article/details/121508271