参考ID如何打印异常



作为对象的参考ID打印className@hash,那么e(异常班级对象的参考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);
    }
    }
}

当您使用java System.out.println(object);中的任何对象时,它将始终调用java object.toString()方法。

Throwable类正在覆盖ToString((方法,以显示所有例外的信息。由于所有例外是可投掷类的子类,因此异常将在 className:Message 格式中显示。

在可投掷类中的tostring((方法的内部实现。

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

在您的情况下,ArithmeticeXception扩展了RuntimeException,RuntimeException扩展了异常,异常扩展了可抛出的。作为Arithmeticexception,RuntimeException和异常类并不是覆盖ToString((方法。这就是执行可投掷tostring((方法的原因。

如果可投掷也不能覆盖toString((,则它将执行 java.lang.object 的toString((,该具有如下

的默认实现
 public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
 }

最新更新