我只是在学习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()
换句话说,存储传递给构造函数的消息字符串的字符串变量的名称是什么,我可以手动设置它是final还是private,如果可以的话,可以使用任何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());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句