温馨提示×

Java异常处理中如何传递错误参数

小樊
83
2024-08-30 08:56:36
栏目: 编程语言

在Java异常处理中,可以通过创建自定义异常类并在其构造函数中接收错误参数来传递错误参数。以下是一个简单的示例:

  1. 首先,创建一个自定义异常类,继承自Exception类:
public class CustomException extends Exception {
    private String errorCode;
    private String errorMessage;

    public CustomException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}
  1. 然后,在需要抛出异常的地方使用这个自定义异常类:
public class Main {
    public static void main(String[] args) {
        try {
            throwCustomException("E001", "This is a custom error message.");
        } catch (CustomException e) {
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
        }
    }

    public static void throwCustomException(String errorCode, String errorMessage) throws CustomException {
        throw new CustomException(errorCode, errorMessage);
    }
}

在这个示例中,我们创建了一个名为CustomException的自定义异常类,它包含两个错误参数:errorCodeerrorMessage。在throwCustomException方法中,我们抛出了一个新的CustomException实例,并传递了这两个参数。在main方法中,我们捕获了这个异常,并打印出了错误代码和错误消息。

0