javase5study

57 阅读2分钟

    异常注意事项
        1.父类方法没有抛出异常,子类覆盖父类该方法时也不可抛出异常。---重点掌握
       此时子类产生该异常,只能捕获处理,不能声明抛出
 
package com.itheima.five;

/*
    Demo04Exception中异常对象是由JVM创建并自动抛出的
        如果我们想自己创建异常对象并手动抛出
        需要使用throw关键字
        throw关键字: 是一个动词,扔,抛的意思
        throw关键字使用格式:
            throw 异常对象;
            throw new 异常类(...);
        注意:
            1.throw必须使用在方法内部
            2.throw后面必须写异常对象,而且只能写一个
            3.throw表示把一个具体的异常对象抛出给该方法的调用者
*/
public class Demo05Throw {
    public static void main(String[] args) {
        int[] array = {100, 200, 300};
        array = null;
        int value = getValue(array, 5);
        System.out.println("main方法中正确获取到数组元素值: " + value);
    }

    public static int getValue(int[] array, int index) {
        //判断如果数组是null,直接抛出空指针异常
        if (array == null) {
            throw new NullPointerException("脑子被xxx踢了,数组是: "+array+", 无法获取元素了");
        }
        //判断如果索引超出范围,直接抛出数组索引越界
        if (index < 0 || index >= array.length) {
            throw new ArrayIndexOutOfBoundsException("你个不长眼的,数组索引: "+index+"超出范围了,无法获取元素");
        }
        int value = array[index];
        System.out.println("getValue方法中正确获取到数组元素值: " + value);
        return value;
    }
}

package com.itheima.five;

import java.io.FileNotFoundException;
import java.text.ParseException;

/*
    多个异常使用捕获又该如何处理呢?
        1. 多个异常分别处理。
        2. 多个异常一次捕获,多次处理。
            异常的父类只能写在最后面,不能写在前面
        3. 多个异常一次捕获一次处理。

    快捷键:
        alt + 回车--> 第一项: throws
        alt + 回车--> 第二项: try-catch
        选定代码 --> ctrl + alt + t --> try-catch
 */
public class Demo08DuoTryCatch {
    public static void main(String[] args) {

        /*
            2. 多个异常一次捕获,多次处理。
                异常的父类只能写在最后面,不能写在前面
            多个catch中的异常类,如果有继承关系,父类只能写在下面
         */

        try {
            a();
            b();
        } /*catch (Exception e) { //错误: 索引的异常都是Exception的子类,产生多态,后面的catch就没机会了
            e.printStackTrace();
        } */catch (ParseException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //3. 多个异常一次捕获一次处理。
        try {
            a();
            b();
        } catch (Exception e) {//多态: 所有异常都当成Exception使用
            e.printStackTrace();
        }
    }
    public static void a() throws ParseException {
        throw new ParseException("解析文件失败", 2);
    }

    public static void b() throws FileNotFoundException {
        throw new FileNotFoundException("文件不存在");
    }
}

package com.itheima.five;
//自定义编译时期异常: 用户名已经被注册的异常类
public class UserNameRegisterException extends Exception {
    //根据父类生成构造方法
    //空参构造
    public UserNameRegisterException() {
    }
    //满参构造
    public UserNameRegisterException(String message) {
        super(message);
    }
}