异常----finally代码块

来源:互联网 发布:大宗商品交易软件排名 编辑:程序博客网 时间:2024/06/06 09:57
class Demo2{    public int show(int index)    {        if(index < 0)            throw new ArrayIndexOutOfBoundsException("越界啦!!");        int[] arr = new int[3];        return arr[index];    }}public class ExceptionDemo5 {    public static void main(String[] args) {        Demo2 d = new Demo2();        //我们看到show方法抛出异常,那我们就需要try一try        try        {            int num = d.show(-3);            System.out.println("num="+num);        }        catch(ArrayIndexOutOfBoundsException e)        {            System.out.println(e.toString());            //我们在这里打输出语句只是举个例子            //catch里写的解决方法不要太简单,至少是简单的日志语句。            //此处加一个return语句             //return ;            //比较运行结果发现,加return语句的前后都执行了finally代码块。            //得知 finally代码块是一定执行的代码块。            //只有一种情况能退出不执行            System.exit(0);//退出jvm        }        //finally的使用场景:        /*         连接数据库         查询。若在此处出现了exception 则后面的关闭连接就无法执行。         关闭连接。这一步骤是必须执行的的。因此放在finally中。         */        finally//通常用于关闭(释放)资源。        {            System.out.println("finally");        }        System.out.println("over");        /*         try catch finally 代码块组合特点:         1,try catch finally          2,try catch(多个) 当没有必要资源需要释放时,可以不用定义finally。         3,try finally 异常无法直接catch处理,但是资源需要关闭。         void show() throws Excepetion         {            try            {                //开启资源。                //出现异常                //抛出                throw new exception();            }            finally            {                //关闭资源。            }         */    }}
原创粉丝点击