如何在我的自定义exception中设置我自己的消息,可以检索我的getMessage()但是没有使用构造函数,有什么办法吗?

我刚学习Java中的exception处理。 我想知道的不是尝试说:

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

不,没有办法手动设置消息,但您可以只使用自己的变量并覆盖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()); } } 

String存储传递给构造函数的消息字符串的变量,我可以手动设置它

Java中没有这样的字段。

但为了帮助您,我建议使用ArrayList来存储Exceptions Strings。 您可以使用add()remove()indexOf()方法轻松地使用此操作数据。 您可以在此处找到有关课程的所有其他信息。

请记住,这不仅是存储数据集的方法,因此我建议您阅读文档。