为什么异常calss引用变量用java打印消息?
我是java新手,我不明白为什么异常类引用变量打印消息,而普通类的引用变量打印消息eclassname@jsjka为什么?为什么异常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
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())