随码网随码网

自定义异常类的使用讲解

自定义异常类的使用讲解

当在特定业务场景的时候,目前已有的异常类不能满足要求,所以需要我们自己自定义异常类,先看看怎么用吧:

第一步:

需要定义一个名为 CustomException 的异常类。在Java中,自定义异常类通常需要继承自标准的异常类,如 Exception 或其子类,以便符合异常类的继承体系。

如何创建一个自定义异常类 CustomException:

public class CustomException extends Exception {

    // 添加一个无参构造方法
    public CustomException() {
        super();
    }

    // 添加一个带消息参数的构造方法
    public CustomException(String message) {
        super(message);
    }

    // 添加一个带消息和原因参数的构造方法
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
}

接下来就是第二步,抛出自定义异常和处理异常:

try {
    // 一些可能引发 CustomException 的代码
    if (someCondition) {
        throw new CustomException("Something went wrong");
    }
} catch (CustomException e) {
    // 捕获 CustomException 异常并处理它
    System.out.println("CustomException caught: " + e.getMessage());
    // 可以执行其他处理操作
}

这样子我们就捕获了异常,控制台打印出:CustomException caught: Something went wrong

下面再来看看多个自定义异常的使用:

try {
    // 一些可能引发异常的代码
    if (someCondition) {
        throw new CustomException("Something went wrong");
    } else if (anotherCondition) {
        throw new AnotherException("Another error occurred");
    }
} catch (CustomException e) {
    // 捕获 CustomException 异常并处理它
    System.out.println("CustomException caught: " + e.getMessage());
    // 可以执行 CustomException 的处理操作
} catch (AnotherException e) {
    // 捕获 AnotherException 异常并处理它
    System.out.println("AnotherException caught: " + e.getMessage());
    // 可以执行 AnotherException 的处理操作
}

这就是自定义异常类的使用,其实和正常的异常类处理是一样的,只不过要先创建自己的异常类而已

未经允许不得转载:免责声明:本文由用户上传,如有侵权请联系删除!

赞 ()

评论