java中的异常

java中的异常

1.1 自定义异常

就和名字一样,就是自己定义的异常,自定义异常同样分为自定义运行时异常和自定义检查型异常

先来看自定义运行时异常

该异常同样在编译时不会产生,在运行时产生,自定义运行时异常同样要继承RuntimeException

package com.example.error;

public class ItheimaAgeRuntimeException extends RuntimeException{
    public ItheimaAgeRuntimeException(String message) {
        super(message);
    }
    public ItheimaAgeRuntimeException() {
        super();
    }
}

这是一个例子,下面是使用:

package com.example.error;

public class MyError {
    public static void main(String[] args) {
        try {
            save(300);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    public static void save(int age){
        if(age<0||age>200){
            throw new ItheimaAgeRuntimeException("年龄数值非法");
        }
        else {
            System.out.println("保存年龄数据");
        }
    }

}

我在接受到异常后选择catch然后输出看着结果和直接向jvm虚拟机抛出异常是一样的,实际上并不同,我们选择

打印异常信息后程序还会继续执行,但如果直接向jvm抛出异常,打印异常信息后程序会终止进行。

接下来我们来看检查型异常

该异常产生后直接在编译时产生错误,而且必须要通过try-catch或者trows进行处理

下面是例子:

package com.example.error;

public class ItheimaAgeException extends Exception{
    public ItheimaAgeException(String message) {
        super(message);
    }
    public ItheimaAgeException() {
        super();
    }
}

该异常继承了Exception ,重写了含参构造器和无参构造器,下面是使用

package com.example.error;

public class MyError {
    public static void main(String[] args)  {

        try {
            save(300);
        } catch (ItheimaAgeException e) {
            e.printStackTrace();
        }

    }
    public static void save(int age) throws  ItheimaAgeException{
        if(age<0||age>200){
            throw new ItheimaAgeException("年龄数值非法");
        }
        else {
            System.out.println("保存年龄数据");
        }
    }

}

通过 throw new ItheimaAgeException("年龄数值非法"); 我们产生并抛出了一个检查型异常给函数,此时必须

要进行处理,使用throws ItheimaAgeException将其进行抛出,到了外层,在外层进行try-catch完成了处理。

posted @ 2025-03-21 17:35  折翼的小鸟先生  阅读(11)  评论(0)    收藏  举报