how to set message to a custom exception class without setting through super constructor in java

我们两清 提交于 2019-12-11 05:27:17

问题


I want to process the variable and set the message but it is not possible as I am only allowed to call the super constructor at the first line only.Is there a way so that I can can set the exception message without calling the super constructor.


回答1:


You are not Forced to call súper constructor always, bit if you do it, must be at the first line.

In this case, use an init block which runs before constructor.




回答2:


The message part of the exception is immutable and only able to set it during the construction of the message. The intention of the Exception is to capture a snapshot of an Error or out of the norm for an event. Not only the Exception capture the message(immutable) but other information such as stacktrace(mutable) as well. You can however, create your own Exception class that override the getMessage(), contructor and setMessage() to store the message yourself.

public class ServiceException extends RuntimeException {
   private static final long serialVersionUID = 1L;
   private String msg;

   public ServiceException() {
   }

   public ServiceException(String msg) {
      super(msg);
      this.msg = msg;
   }

   public ServiceException(Throwable ex) {
      super(ex);
      this.msg = ex.getMessage();
   }

   public ServiceException(String msg, Throwable ex) {
      super(msg, ex);
      this.msg = msg;
   }

   @Override
   public String getMessage() {
      return msg;
   }

   public void setMessage(String msg) {
      this.msg = msg;
   }
}



回答3:


Steps to follow:

  • create a separate class that will first process the variable and create your custom message

  • finally pass the processed message to the custom exception class

This process will make the objects more cohesive.


EDIT

Sample code:

public class MyException extends Exception{
    public MyException(String message){
        super(MessageProcesser.processMessage(message));
    }
}

public class MessageProcesser{
    public static String processMessage(String message){
        // return processed message
    }
}


来源:https://stackoverflow.com/questions/22216478/how-to-set-message-to-a-custom-exception-class-without-setting-through-super-con

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!