java006学习记录

本文详细阐述了Java中的throw关键字用于主动抛出异常,以及异常的自动检测和处理机制。介绍了如何使用try-catch捕获异常,以及throws关键字在方法声明中的应用。同时,讨论了自定义异常的创建和使用规则。
摘要由CSDN通过智能技术生成

异常

throw 和 throws

throw 是主动抛出异常,手动创建一个异常对象,抛出

异常是 Java 自主机制,Java 自动执行异常的流程

1、检测所有的代码,类加载的阶段仅仅进行语法错误的检查,编译,再运行,在运行阶段进行检测

2、发现运行时错误,则根据错误类型创建一个对应的异常对象,并抛出

3、对异常对象进行处理,手动 try-catch 代码进行捕获,交给 Java 虚拟机进行处理

package test;

public class Test {
    public static void main(String[] args) throws Exception {
        String str = "Jav";
        test(str);
    }

    public static void test(String string){
        try{
            if(!string.equals("Java")){
                //主动创建异常对象
                RuntimeException runtimeException = new RuntimeException("单词拼写错误");
                //抛出异常
                throw runtimeException;
            } else {
                System.out.println("ok");
            }
        }catch (Exception e){
            System.out.println("异常类型:"+e.getClass()+",异常信息:"+e.getMessage());
        }

    }

}

Java 默认异常机制只能满足最基础的操作,真正的企业级项目中是远远不够的,需要手动结合具体业务场景进行异常的创建及抛出。

throws 标识方法可能会出现某些异常,修饰方法的

并不是每个方法都需要进行修饰,风险较大(抛出异常的概率)的方法需要进行标识,风险小的不需要进行标识。

给方法添加标识的目的是告诉开发者该方法需谨慎调用,该 try-catch 就需要 try-catch

package test;

public class Test {
    public static void main(String[] args) {
        test3();
    }

    public static void test(String string){
        try{
            if(string.equals("a")){
                throw new ArithmeticException();
            }
            if(string.equals("b")){
                throw new NullPointerException();
            }
            if(string.equals("c")){
                throw new ArrayIndexOutOfBoundsException();
            }
        } catch (RuntimeException e){
            System.out.println("【异常】类型:" + e.getClass() + "信息:" + e.getMessage());
        }

    }

    public static void test4() throws Exception{
        test3();
    }

    public static void test3() {
        try {
            test2("1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void test2(String string) throws Exception {
        int i = Integer.parseInt(string);
        System.out.println(i);
    }

}

自定义异常

Java 提供的异常类无法满足一些特定业务需求的时候,开发者自己进行扩展即可,继承

方法中抛出的异常类(本身或者其父类)是 Exception 的时候,必须给方法添加 throws 修饰

如果方法中抛出的异常类(本身或其父类)是 RuntimeException,则不需要进行 throws 的修饰

package test;

public class MyNumberException extends Exception {
    public MyNumberException(String message){
        super(message);
    }
}
public static void add(Object object) throws Exception {
    //如何判断object是否为Integer类型?
    if(!(object instanceof Integer)){
        throw new MyNumberException("【传入的参数不是整数类型】");
    } else {
        int num = (int) object;
        num++;
        System.out.println(num);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值