Java学习 第二十五章 异常/throw关键字/throws/try...catch/finally代码块

第二十五章

一、异常概念&异常体系

1.1 异常

抛出异常就是把异常交给出现异常程序的上一级程序处理。处理不了,最终会交给JVM处理。
异常:指的是程序在程序执行的过程中,出现的非正常的情况,最终会导致JVM非正常停止,在Java等面向对象的编程语言中,异常本身就是一个类,产生异常就是创建异常对象,并抛出了一个异常对象。Java处理异常的方式是 中断处理

1.2 异常体系

Throwable 类是 Java 语言中所有错误或异常的超类。
从前从前,有位老人,他的名字叫Throwable,他生了两个儿子,大儿子叫Error,二儿子叫Exception。

Error

表示编译时或者系统错误,如虚拟机相关的错误,OutOfMemoryError等,error是无法处理的。

Exception

代码异常,Java程序员关心的基类型通常是Exception。它能被程序本身可以处理,这也是它跟Error的区别。

1.3 异常分类

/*
    Java.lang.Throwable:类是Java语言中所有错误或异常的超类
       Exception:编译期异常,进行编译(写代码)java程序出现的问题
           RuntimeException:运行期异常,java程序运行过程中出现的问题
              异常就相当于得了一个小毛病(感冒、发烧),把异常处理掉,程序可以继续执行(吃点药继续工作)

     Error:错误
            错误就相当于程序得了绝症,必须修改源代码,程序才能继续执行
 */
public class Demo01Exception {
    public static void main(String[] args) /*throws ParseException*/ {
       // Exception:编译期异常,进行编译(写代码)java程序出现的问题
  /*      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//用来格式化日期
        Date date = null;//把字符串格式的日期,解析为Date格式的日期
        try {//try catch 把异常处理之后,后边的程序能继续执行
            date = sdf.parse("1999-0909");//把字符串格式的日期,解析为Date格式的日期
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);*/


//   RuntimeException:运行期异常,java程序运行过程中出现的问题
//        int[] arr = {1,2,3};
//     //   System.out.println(arr[0]);
//        try {
//            //可能会出现异常的代码
//            System.out.println(arr[3]);//ArrayIndexOutOfBoundsException索引越界异常
//
//        }catch(Exception e){
//            //异常的处理逻辑
//            System.out.println(e);
//
//        }

        /*
          Error:错误
        */
        //OutOfMemoryError: Java heap space 内存溢出错误,超出了给JVM分配的内存
     //   int[] arr = new int[1024*1024*1024];
        //必须修改代码

        System.out.println("后续代码");
    }
}

1.3 异常的产生过程分析

在这里插入图片描述

1.4 throw关键字(抛出异常)

/*
    throw 关键字
    作用:
        可以使用throw关键字,在指定的方法中抛出指定的异常
     使用格式:
         throw new xxxException("异常产生的原因")
     注意:
        1.throw关键字必须写在方法的内部
        2.throw关键字后边必须是Exception或者Exception的子类对象
        3.throw关键字抛出指定的异常对象,我们就必须处理这个异常对象
            throw关键字后边创建的是RuntimeException或者是RuntimeException的子类对象,
            我们可以不处理,默认交给JVM处理(打印异常对象,中断程序)
            throw关键字后边创建的是编译异常(写代码的时候报错),我们就必须处理这个异常,
            要么throws要么try...catch
          注意:
          NullPointerException是一个运行期异常,我们不用处理,默认交给JVM处理
          ArrayIndexOutOfBoundsException是一个运行期异常,我们不用处理,默认交给JVM处理

 */
public class Demo03Throw {
    public static void main(String[] args) {
     //   int[]  arr = null;
        int[]  arr = new int[3];
        int element = getElement(arr,3);
        System.out.println(element);
    }

    /*
  定义一个方法,获取数组指定索引处的元素
  参数:
        int[] arr
        int index
        以后我们首先必须对方法传递过来的参数进行合法性的校验
        如果参数不合法,那么我们就必须使用抛出异常的方式,告知方法的调用者,传递的参数有问题
   */
    public static int getElement(int[] arr,int index){
        /*
        我们可以对传递过来的参数数组,进行合法性校验
        如果数组arr的值是null
        那么我们就抛出空指针异常,告知方法的调用者”传递的数组的值是null“
         */
        if(arr == null){
         throw   new NullPointerException("传递的数组的值是null");
        }
        /*
        我们可以对传过来的参数index进行合法性校验
        如果index的范围不再数组的索引范围内
        那么我们就抛出数组索引越界异常,告知方法的调用者"传递的索引超出了数组的使用范围"
         */
        if(index < 0 || index > arr.length){
            throw  new ArrayIndexOutOfBoundsException("数组索引越界");
        }
        int ele = arr[index];
        return ele;
    }
}

1.5 Objects非空判断

Objects类,由一些静态的实用方法组成,这些方法是null-save(空指针安全的)或null-tolerant(容忍空指针的),那么在它的源码中,对对象为null的值进行了抛出异常操作。

/*
    Objects类中的静态方法
    public static <T> requiredNonNull(T obj):查看指定引用对象不是null
    源码:
        public static <T> T requiredNonNull(T obj){
                if(obj == null){
            throw new NullPointerException();
            return obj;
        }
        }
 */
public class Demo04Objects {
    public static void main(String[] args) {
        method(null);
    }

    public static void method(Object obj){
        //对传递过来的参数合法性判断,判断是否为空
  /*      if(obj == null){
            throw new NullPointerException("传递对象的值是null");
        }*/
       // Objects.requireNonNull(obj);
        //方法的重载
        Objects.requireNonNull(obj,"递对象的值是null");

    }
}

1.6 声明异常throws–异常处理的第一种处理方式,交给别人处理

/*
    throws关键字:异常处理的第一种方式,交给别人处理
    作用:
        当方法内部抛出异常的时候,那我们就必须处理这个异常对象
        可以使用throws关键字处理异常对象,会把异常对象声明抛出给方法的调用者处理
            (自己不处理,给别人处理),最终交给JVM处理-->中断处理
     使用格式:在方法声明时使用
            修饰符 返回值类型 方法名(参数列表) throws{
                throw new AAAException(“产生原因”);
                throw new AAAException(“产生原因”);
                ...
              }
       注意:
            1.throws关键字必须写在方法声明处
            2.throws关键字后边声明的异常必须是Exception或者是Exception的子类
            3.方法内部如果抛出了多个异常对象,那么throws后边必须也声明多个异常
                如果抛出多个异常对象有子父类关系,那么直接声明父类异常即可
            4.调用了一个声明抛出异常的方法,我们就必须处理声明的异常
                    要么继续使用throws声明抛出,交给方法的调用者处理,最终交给JVM
                    要么try...catch自己处理异常

 */
public class Demo05Throws {
    /*
        FileNotFoundException extends IOException extends Exception
    如果抛出多个异常对象有子父类关系,那么直接声明父类异常即可
     */

                                        //throws 交给JVM处理
    //public static void main(String[] args) throws FileNotFoundException,IOException {
    public static void main(String[] args) throws Exception {
        redFile("c:\\a.txt");

    }
    /*
        定义一个方法,对传递的文件路径进行合法性判断
        如果路径不是“c:\\a.txt”,那么我们就抛出文件找不到异常对象,告知方法的调用者
        注意:
            文件找不到异常  是编译异常,抛出了编译异常,就必须处理这个异常
            可以使用throws继续声明抛出FileNotFoundException这个异常,让方法调用者处理

     */

    public static void redFile(String filename) throws FileNotFoundException,IOException{
        if (!filename.equals("c:\\a.txt")){
            throw new FileNotFoundException("传递的文件路径不是c:\\a.txt");
        }
        /*
            如果传递的路径,不是.txt结尾
            那么我们就抛出IO异常对象,告知方法的调用者,文件的后缀名不对
         */
        if (!filename.endsWith(".txt")){
            throw new IOException("文件的后缀名不对");
        }
        System.out.println("路径没有问题,读取文件");
    }

}

1.6 try…catch–异常处理的第一种处理方式

在这里插入图片描述

/*
    try...catch:异常处理的第二种方式,自己处理异常
    格式:
        try{
            可能产生异常的代码
        }catch(定义一个异常的变量,用来接受try中抛出的异常对象){
            异常的处理逻辑,产生异常对象之后,怎么处理异常
            一般在工作中,会把异常的信息记录到一个日志中
        }...
        catch(异常数据类型 变量名){

        }
    注意:
        1.try中可能会抛出多个异常对象,那么就可以使用多个catch来处理这些异常对象
        2.如果try中产生了异常,那么就会执行catch中的异常处理逻辑,执行完毕catch中的处理逻辑,
        继续执行try...catch之后的代码,
        如果try中没有产生异常,那么就不会执行catch中的异常的处理逻辑,执行完try中的代码。继续执行
        try...catch之后的代码

 */
public class Demo06TryCatch {
    public static void main(String[] args) {
        try {
            //可能产生异常的代码
            redFile("c:\\a.txt");
        } catch (IOException e) {//try中抛出什么异常对象,catch就定义什么异常变量,用来接收这个异常对象
           // 异常的处理逻辑,产生异常对象之后,怎么处理异常
            System.out.println("catch - 传递的文件后缀不是.txt");
        }
        System.out.println("后续代码");
    }
    /*
           如果传递的路径,不是.txt结尾
           那么我们就抛出IO异常对象,告知方法的调用者,文件的后缀名不对
        */
    public static void redFile(String filename) throws  IOException {
        if (!filename.equals("c:\\a.txt")){
            throw new FileNotFoundException("传递的文件路径不是c:\\a.txt");
        }

        if (!filename.endsWith(".txt")){
            throw new IOException("文件的后缀名不对");
        }
        System.out.println("路径没有问题,读取文件");
    }

}

1.7 Throwable类中三个异常处理的方法

public class Demo06TryCatch {
    public static void main(String[] args) {
        try {
            //可能产生异常的代码
            redFile("d:\\a.tx");
        } catch (IOException e) {//try中抛出什么异常对象,catch就定义什么异常变量,用来接收这个异常对象
           // 异常的处理逻辑,产生异常对象之后,怎么处理异常
          //  System.out.println("catch - 传递的文件后缀不是.txt");

            /*
                Throwable类中定义的三个处理异常的方法
             */
            //String getMessage() 返回此throwable的简短描述
           // String toString()返回此throwable的详细详细字符串
            //void  printStackTrace() JVM打印异常对象,默认此方法,打印的异常信息是最全面的
           // System.out.println(e.getMessage());//文件的后缀名不对
           // System.out.println(e.toString());//重写Object类的toString
           // System.out.println(e);//文件的后缀名不对
            e.printStackTrace();
/*
            java.io.FileNotFoundException: 传递的文件路径不是c:\a.txt
            at cn.itcast.day14.demo04.Demo06TryCatch.redFile(Demo06TryCatch.java:59)
            at cn.itcast.day14.demo04.Demo06TryCatch.main(Demo06TryCatch.java:30)*/




        }
        System.out.println("后续代码");
    }
    /*
           如果传递的路径,不是.txt结尾
           那么我们就抛出IO异常对象,告知方法的调用者,文件的后缀名不对
        */
    public static void redFile(String filename) throws  IOException {

        if (!filename.endsWith(".txt")){
            throw new IOException("文件的后缀名不对");
        }
        System.out.println("路径没有问题,读取文件");
    }

}

1.8 finally代码块

/*
    finally代码块:
        格式:
            try{
            可能产生异常的代码
             }catch(定义一个异常的变量,用来接受try中抛出的异常对象){
                异常的处理逻辑,产生异常对象之后,怎么处理异常
                一般在工作中,会把异常的信息记录到一个日志中
        }... catch(异常数据类型 变量名){

        }finally{
              无论是否出现异常都会执行
        }
        注意:
            1.finally不能单独使用,必须和try一起使用
            2.finally一般用于资源释放(资源回收),无论程序是否出现异常,最后都要资源释放(IO)
 */
public class Demo07TryCatchFinally {
    public static void main(String[] args) {
        try {
            //可能会产生异常的代码
            redFile("c:\\a.tx");
        } catch (IOException e) {
            //异常处理逻辑
            e.printStackTrace();//打印异常信息,最全
            /*
             //String getMessage() 返回此throwable的简短描述
           // String toString()返回此throwable的详细详细字符串
            //void  printStackTrace() JVM打印异常对象,默认此方法,打印的异常信息是最全面的
             */
        }finally {
            //无论是否出现异常都会执行
            System.out.println("资源释放");
        }

    }



 /*
           如果传递的路径,不是.txt结尾
           那么我们就抛出IO异常对象,告知方法的调用者,文件的后缀名不对
        */

    public static void redFile(String filename) throws IOException {

        if (!filename.endsWith(".txt")){
            throw new IOException("文件的后缀名不对");
        }
        System.out.println("路径没有问题,读取文件");
    }
}

1.9 异常注意事项

/*
    异常的注意事项: 
        多个异常使用捕获又该如何处理呢》
        1.多个异常分别处理
        2.多个异常一次捕获多次处理
        3.多个异常一次捕获,一次处理
 

 */
public class Demo08Exception {
    public static void main(String[] args) {

   
        //1.多个异常分别处理
/*    try{
            int[] arr = {1,2,3};
            System.out.println(arr[3]);//ArrayIndexOutOfBoundsException:
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);

        }
        try{
            List<Integer> lsit = List.of(1, 2, 3);
            System.out.println(lsit.get(4));
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);

        }*/

        //2.多个异常一次捕获多次处理
         /*
         一个try多个catch注意事项:
               catch里边定义的异常变量。如果有子父类关系,那么子类的异常变量必须写在上边,否则就会报错
        ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
         */
   /*     try{
            int[] arr = {1,2,3};
        //    System.out.println(arr[3]);//ArrayIndexOutOfBoundsException:

            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(4));
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);

        } catch (IndexOutOfBoundsException e){
            System.out.println(e);

        }*/

        //3.多个异常一次捕获,一次处理
        try{
            int[] arr = {1,2,3};
            System.out.println(arr[3]);//ArrayIndexOutOfBoundsException:

            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(4));
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
            System.out.println(e);

        }
        //运行时异常被抛出可以不处理,即不捕获也不声明抛出
        //默认给虚拟机处理,终止程序,什么时候不排除运行时异常了,再来执行程序


            int[] arr = {1,2,3};
            System.out.println(arr[3]);//ArrayIndexOutOfBoundsException:
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(4));

        System.out.println("后续代码");

    }
}

1.9.1finally有return语句

在这里插入图片描述

public class Demo09Exception {
    public static void main(String[] args) {
        int a = getA();
        System.out.println(a);

    }
    //定义一个方法,返回变量a的值
    public static int getA(){
        int a = 10;
        try {
            return a;
        }catch (Exception e){
            System.out.println(e);

        }finally {
            //一定会执行的代码 所以尽量不要在finally中写return语句
            a = 100;
            return a;

        }
    }
}

1.9.2 子父类异常

父类异常时什么样,子类异常时就什么样

/*
    子父类的异常:

    注意:
        父类异常时什么样,子类异常时就什么样
 */
public class Fu {
                                                        //类型转换异常
    public void show01() throws NullPointerException,ClassCastException{}
    public void show02() throws IndexOutOfBoundsException{}
    public void show03() throws IndexOutOfBoundsException{}
    public void show04(){}
}

class Zi extends Fu{
    //子类重写父类方法时,抛出和父类相同的异常
    public void show01() throws NullPointerException,ClassCastException{}
    //子类重写父类方法时,抛出父类异常的子类
    public void show02() throws IndexOutOfBoundsException{}
    //子类重写父类方法时不抛出异常
    public void show03(){}
    //父类没有抛出异常,子类重写该方法也不能抛出异常
        //此时子类产生该异常,只能捕获处理,不能声明抛出
    public void show04() {
        try {
            throw new Exception("编译期异常");
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值