3

我只是在学习 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 时遇到了麻烦

4

2 回答 2

14

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


}
于 2014-10-11T09:31:13.513 回答
0

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

Java中没有这样的字段。

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

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

于 2014-10-11T09:31:58.110 回答