在Java中,我们可以通过自定义异常类来定义两个异常。自定义异常类是通过继承Exception
或者其子类来实现的。下面我将通过代码示例和逻辑清晰地说明如何定义两个异常。
首先,我们需要创建一个基类异常,作为其他异常的父类。这个基类异常可以是Exception
类的直接子类,也可以是其他自定义异常类。在这个基类异常中,我们可以添加一些共有的属性和方法,以便在子类异常中复用。
以下是一个基类异常的示例:
public class BaseException extends Exception {
private String errorMessage;
public BaseException(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
}
接下来,我们可以创建两个子类异常,分别代表不同的具体情况。这些子类异常应该继承自基类异常,并可以添加自己特有的属性和方法。
以下是两个子类异常的示例:
public class CustomException1 extends BaseException {
private int errorCode;
public CustomException1(String errorMessage, int errorCode) {
super(errorMessage);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
public class CustomException2 extends BaseException {
private String errorDetail;
public CustomException2(String errorMessage, String errorDetail) {
super(errorMessage);
this.errorDetail = errorDetail;
}
public String getErrorDetail() {
return errorDetail;
}
}
在上面的示例中,CustomException1
和CustomException2
分别添加了errorCode
和errorDetail
两个特有的属性。这样,在捕获这些异常时,我们可以根据需要获取更详细的信息。
现在,我们可以在代码中使用这两个异常。以下是一个简单的示例:
public class ExceptionExample {
public static void main(String[] args) {
try {
throw new CustomException1("Custom exception 1 occurred", 1001);
} catch (CustomException1 e) {
System.out.println(e.getErrorMessage());
System.out.println("Error code: " + e.getErrorCode());
}
try {
throw new CustomException2("Custom exception 2 occurred", "Error details");
} catch (CustomException2 e) {
System.out.println(e.getErrorMessage());
System.out.println("Error detail: " + e.getErrorDetail());
}
}
}
在上面的示例中,我们分别抛出了CustomException1
和CustomException2
异常,并在捕获时打印了相应的错误信息。
通过以上代码示例,我们成功定义了两个自定义异常类,并在程序中使用它们。这种自定义异常类的设计方式使得我们可以根据不同的异常情况灵活地处理错误信息,并提供更详细的异常信息。