作为对象的参考ID会打印className @ hash,那么e(Exception类的对象的参考ID)如何打印异常名称?
class try1{
public static void main(String ...args){
try{
int x = 10/0;
System.out.print(x);
}catch(ArithmeticException e){
System.out.print(e);
}
}
}
答案 0 :(得分:-1)
在java System.out.println(object);
中使用任何对象时,它将始终调用java object.toString()
方法。
Throwable类将重写toString()方法以显示所有异常的信息。由于所有异常都是可抛出类的子类,因此异常将以 className:message 格式显示。
Throwable类中toString()方法的内部实现。
public String toString() {
String s = getClass().getName();
String message = getLocalizedMessage();
return (message != null) ? (s + ": " + message) : s;
}
在您的情况下,ArithmeticException扩展了RuntimeException,RuntimeException扩展了Exception,而Exception扩展了Throwable。作为ArithmeticException,RuntimeException和Exception类不会覆盖toString()方法。这就是执行Throwable toString()方法的原因。
如果Throwable也没有覆盖toString(),它将执行 java.lang.Object 的toString(),其默认实现如下所示
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}