How to set my own message in my custom exception in Java that can be retrieved my getMessage() BUT WITHOUT using the constructor, is there any way?

谁都会走 提交于 2019-12-03 20:08:48

No, there is no way of setting the message manually, you could however just use your own variable instead and override the getMessage() method

Example:

public class MyException extends Exception{

    public String message;

    public MyException(String message){
        this.message = message;
    }

    // Overrides Exception's getMessage()
    @Override
    public String getMessage(){
        return message;
    }

    // Testing
    public static void main(String[] args){
        MyException e = new MyException("some message");
        System.out.println(e.getMessage());
    }


}

String Variable that store the message string passed to the constructor and can i set it manually

There is no such field in Java.

But to help you, i suggest using ArrayListto store Exceptions Strings. You can easily manipulate data with this by using add(),remove(), indexOf() methods . All additional information about class you can find here.

Keep in mind that this is not only way to store sets of data, so i suggest to read documentation.

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