Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么异常calss引用变量用java打印消息?_Java_Tostring - Fatal编程技术网

为什么异常calss引用变量用java打印消息?

为什么异常calss引用变量用java打印消息?,java,tostring,Java,Tostring,我是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

我是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
你看到了你班级的表现。相反,
算术异常
已经覆盖了此方法。您需要在
例外11

@Override
public String toString() {
    return "Exception11 [x=" + x + ", y=" + y + "]";
}

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

对于您的类,将打印默认值,即类名后跟
@
,后跟十六进制的标识哈希代码

您可以覆盖为:

@Override
public String toString() {
    //your logic to construct a string that you feel
       // textually represents the content of your Exception11
}

arithmetricexception
使用
Throwable#toString()
实现:

public String toString() {
    String s = getClass().getName();
    String message = getLocalizedMessage();
    return (message != null) ? (s + ": " + message) : s;
}
当类
异常11
使用默认的
对象时#toString()


调用
System.out.println(“…”+e)
将调用
exception11e的
toString()
方法。由于
Exception11
类没有
toString()
方法,因此它继承了
对象的
toString()
方法,该方法返回一个值为:

getClass().getName() + '@' + Integer.toHexString(hashCode())
这就是
Exception11@4f1d0d
来自。您必须在
Exception11
类中实现
toString()
,并让它返回您希望命名错误的任何字符串


有关
对象
toString()
方法的详细信息,请参见。

以及与JavaEE的关系是什么?
getClass().getName() + '@' + Integer.toHexString(hashCode())