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
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 ArrayList
to 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.
来源:https://stackoverflow.com/questions/26313084/how-to-set-my-own-message-in-my-custom-exception-in-java-that-can-be-retrieved-m