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?

Sainath S.R picture Sainath S.R · Oct 11, 2014 · Viewed 32.6k times · Source

I'm just learning about exception handling in Java. What I would like to know is rather than trying something like say:

throw new Exception("My Message");

and

String message=ex.getMessage();

System.out.println(message);

Take a look at the code below ,

class ExceptionTest {
    public static void main(String[] args) {
        ExceptionTest t1=new ExceptionTest();

        try {
            t1.riskyMethod();//call the risky or exception throwing method
        } catch(MyException myex) {
            System.out.println("Exception has been thrown");

            String message=myex.getMessage();//get the String passed during exception call
            System.out.println("The message retrieved is "+message);
            myex.printStackTrace();//prints name of exception and traces the function call stack
        }

    }//main ends

    void riskyMethod() throws MyException {//a method that can throw an excpetion
        int rand=(int)(Math.random()*10);///Math.rand return 0 to .9 range value

        if(rand>5) {
            //throw new MyException();  or try this
            //      MyException myexception=new MyException();
            //      myexception.setMessage("HI THIS IS A SAMPLE MESSAGE");
            String mymessage="Sample Exception Message...";
            throw new MyException(mymessage);
        }
        else
            System.out.println("No exception");
    }
}//Exception class ends 

While this works fine I want to know if I can avoid calling super(message) etc and just set some variable 'message' in my subclass MyException that changes the message retrieved on a call to exception.getMessage()

In other words what is the name of the string variable that store the message string passed to the constructor and can I set it manually, is it final or private, if so is there any setter method for it. Sorry I tried but am just a beginner and have trouble navigating the API

Answer

SamTebbs33 picture SamTebbs33 · Oct 11, 2014

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());
    }


}