0

我是java新手我不明白为什么异常类引用变量打印消息和普通类的引用变量打印eclassname@jsjka为什么?

public class Exception11 {
    int x,y;

    public static void main(String[] args) {
        try{
        int total;
        Exception11 e=new Exception11();
        e.x=10;
        e.y=0;
        total=10/0;
        System.out.println("Value of refernce variable: "+e);
        System.out.println(total);
        } catch (ArithmeticException h) {
            System.out.println("number can not divide by the 0 Please try again");
            int total;
            Exception11 e=new Exception11();
            System.out.println("Value of refernce variable: "+e);
            System.out.println("Value of refernce variable: "+h);



        }

    }

}

回答 - - - - - - - - - - - - - - -

number can not divide by the 0 Please try again
Value of refernce variable: Exception11@4f1d0d
Value of refernce variable: java.lang.ArithmeticException: / by zero
4

4 回答 4

4

You're seeing the Object#toString representation of your class. In contrast ArithmeticException already overrides this method. You need to override this method in Exception11

@Override
public String toString() {
    return "Exception11 [x=" + x + ", y=" + y + "]";
}
于 2013-10-22T21:17:33.020 回答
2

调用System.out.println("..." + e)将调用 的toString()方法Exception11 e。由于Exception11该类没有toString()方法,因此它继承了ObjecttoString()方法,该方法返回String带有值的 a:

getClass().getName() + '@' + Integer.toHexString(hashCode())

这是Exception11@4f1d0d从哪里来的。您必须toString()在您的Exception11类中实现并让它返回您希望命名错误的任何字符串。

有关'方法Object#toString()的详细信息,请参阅。ObjecttoString()

于 2013-10-22T21:23:44.257 回答
1

您正在打印h.toString()e.toString(). 因为ArithmeticException有一个被toString打印的覆盖自定义。

对于您的班级,将打印默认值,即班级名称后跟@十六进制的身份哈希码。

您可以覆盖为:

@Override
public String toString() {
    //your logic to construct a string that you feel
       // textually represents the content of your Exception11
}
于 2013-10-22T21:17:48.170 回答
1

ArithmeticException使用Throwable#toString()实现:

public String toString() {
    String s = getClass().getName();
    String message = getLocalizedMessage();
    return (message != null) ? (s + ": " + message) : s;
}

而您的班级Exception11使用默认值Object#toString()

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
于 2013-10-22T21:18:07.720 回答