我只是在学习 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
虽然这很好用,但我想知道我是否可以避免调用 super(message) 等,只需在我的子类 MyException 中设置一些变量“message”,它会更改调用 exception.getMessage() 时检索到的消息
换句话说,存储传递给构造函数的消息字符串的字符串变量的名称是什么,我可以手动设置它,它是最终的还是私有的,如果是的话,是否有任何 setter 方法。抱歉,我试过了,但我只是一个初学者,在导航 API 时遇到了麻烦