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 に変数「メッセージ」を設定して、例外への呼び出しで取得されたメッセージを変更できるかどうかを知りたいです。getMessage()
言い換えれば、コンストラクターに渡されたメッセージ文字列を格納する文字列変数の名前は何ですか?手動で設定できますか?最終またはプライベートですか?そうであれば、セッターメソッドがあります. 申し訳ありませんが、試してみましたが、初心者であり、API の操作に問題があります