java - 为什么异常类引用变量在java中打印消息?

标签 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;
        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

最佳答案

您看到的是Object#toString代表你的类(class)。相反,ArithmeticException 已经覆盖了此方法。您需要在Exception11

中重写此方法
@Override
public String toString() {
    return "Exception11 [x=" + x + ", y=" + y + "]";
}

关于java - 为什么异常类引用变量在java中打印消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528502/

相关文章:

java - 将 EntityManager 对象传递给所有 BusinessLayer 方法

java - 在抽象父类中重写 toString() 是个好主意吗?

javascript - 获取 Array.toString() 的结果,而不用逗号分隔项目

java - 打印 arrayList 时出现空值?

java - 移除对象会导致卡住

java - 如何使用意图检索双数据?

java - Java 格式化 toString

c++ - 为 std::to_string() 获取自己的补丁,以便在旧编译器上与 double 一起正常工作

java - Netbeans 中的 Jaxb 错误

Java自定义注解查找方法