Java中重写异常

Java中重写异常,java,exception,Java,Exception,我创建了一个自定义类,用于处理项目中发生的异常。我的要求是更改异常的消息,并将一些数据附加到异常消息中,然后将其传递给我的自定义类 因此,本质上,我需要在设置异常消息后编辑它 有什么方法可以做到这一点吗?您可以重写异常类的getMessage方法 public class Student { checkAge (Student student) { try { if (student.getAge() > 18 ) {

我创建了一个自定义类,用于处理项目中发生的异常。我的要求是更改异常的消息,并将一些数据附加到异常消息中,然后将其传递给我的自定义类

因此,本质上,我需要在设置异常消息后编辑它


有什么方法可以做到这一点吗?

您可以重写
异常
类的
getMessage
方法

public class Student {

    checkAge (Student student) {
        try {
            if (student.getAge() > 18 ) {
                throw new CustomException("Student is older than 18 years.");
            }
        } catch (CustomException e) {
            handleException(e);
        }
    } 


public class HandleException {
    public static sendToErrorReport (CustomException customException) {
        //trying to do something like this, but the below code throws an error.
        customException.setMessage(customException.getMessage() +" ; Student -> " + customException.getStudent().getStudentName);
    }
}

您可以重写
Exception
类的
getMessage
方法

public class Student {

    checkAge (Student student) {
        try {
            if (student.getAge() > 18 ) {
                throw new CustomException("Student is older than 18 years.");
            }
        } catch (CustomException e) {
            handleException(e);
        }
    } 


public class HandleException {
    public static sendToErrorReport (CustomException customException) {
        //trying to do something like this, but the below code throws an error.
        customException.setMessage(customException.getMessage() +" ; Student -> " + customException.getStudent().getStudentName);
    }
}

在代码中引发异常时

试试看{
//这里有一些代码
}捕获(例外e){
抛出新的CustomeException(“此处的文本”)
}
当您在其他地方捕获CustomeException时,您可以对其进行修改

试试看{
//这里有一些代码
}捕获(自定义异常){
String message=e.getMessage();
//用上一条消息做一些事情
抛出新的Custom2Exception(“此处的下一个文本”)
}

在代码中引发异常时

试试看{
//这里有一些代码
}捕获(例外e){
抛出新的CustomeException(“此处的文本”)
}
当您在其他地方捕获CustomeException时,您可以对其进行修改

试试看{
//这里有一些代码
}捕获(自定义异常){
String message=e.getMessage();
//用上一条消息做一些事情
抛出新的Custom2Exception(“此处的下一个文本”)
}

这里是扩展RuntimeException类的完整CustomException类。您可以定义代码和消息

class CustomException extends java.lang.Exception{

    @Override
    public String getMessage(){
        return super.getMessage() + "- My Message";
    }

}

下面是扩展RuntimeException类的完整CustomException类。您可以定义代码和消息

class CustomException extends java.lang.Exception{

    @Override
    public String getMessage(){
        return super.getMessage() + "- My Message";
    }

}

发布示例代码?以正确理解:(1)捕获异常并重新引发其他异常,或(2)使用
@Override getMessage(){return super.getMessage()+…}
?发布示例代码?以正确理解:(1)捕获异常并重新引发其他异常,或(2)抛出一个子异常,该异常包含一个
@Override getMessage(){return super.getMessage()+…}