我刚学习Java中的异常处理.我想知道的不是尝试说:
throw new Exception("My Message");
和
String message=ex.getMessage();
System.out.println(message);
看看下面的代码,
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
虽然这很好,我想知道我是否可以避免调用超级(消息)等
并在我的子类MyException中设置一些变量’message’,它更改在调用exception.getMessage()时检索到的消息
换句话说,存储传递给构造函数的消息字符串的字符串变量的名称是什么,我可以手动设置它,是最终的还是私有的,如果有的话,有任何setter方法.对不起,我试过,但我只是一个初学者,无法浏览API
解决方法:
不,没有办法手动设置消息,但是你可以只使用自己的变量并覆盖getMessage()方法
例:
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());
}
}