【问题标题】:Overriding toString() in Exception Handling在异常处理中重写 toString()
【发布时间】:2014-12-21 13:23:29
【问题描述】:
public class ExcepHand  {
    public String toString()
    {
        return "Exception Occured";
    }
    public static void main(String args[])
    {
        int a=10;
        int b=0;
        try
        {
            int c=a/b;
        }
        catch(ArithmeticException e)
        {
            System.out.println(e);
        }
    }
}

这给了我一个输出java.lang.ArithmeticException: / by zero。我想知道为什么toString() 方法没有被覆盖。如果可以的话,请告诉我怎么做。

【问题讨论】:

  • 因为在您的代码中没有任何时候在 ExcepHand 的实例上调用 toString。
  • toString() 在捕获到异常时不会被调用。要在这种情况下调用toString(),您必须创建ExcepHand 的实例,例如ExcepHand obj = new ExcepHand(),然后调用obj.toString()
  • 我强烈建议您阅读有组织的 Java 教程。

标签: java tostring overriding


【解决方案1】:

您更改了ExcepHand 类的toString(),而不是java.lang.ArithmeticException 类的toString()

如果你想写另一个日志消息,你可以简单地写一个字符串,如果你捕获了一个 ArithmeticException。

异常处理的一些想法:

你捕获一个异常,如果你简单地记录消息,你将丢失行和类信息。你最好打电话给printStacktrace()

稍后您应该开始查看日志记录框架,例如 log4jjava.util.logging

【讨论】:

    【解决方案2】:

    你需要这样的东西:

    try {
        int c=a/b;
    }
    catch(ArithmeticException e) {
        System.out.println(new ExcepHand());//it will automatically call toString of you ExceptHand object but an ugly way to do it.
    }
    

    您正在调用 ArithmeticException 的 toString 方法,而不是 ExcepHand。

    【讨论】:

    • 这会调用toString(),但似乎真的没用,因为在这种情况下他可以直接写行。
    • 我同意。但是对于 OP 的理解,我使用了如此丑陋的代码。
    • 你是对的,但我认为最好提一下“这会使你的代码工作,但你不应该这样做”。
    • 是的,我确实在我的评论中提到了它,回答“你是 exceptHand 对象,但这样做的方式很丑陋。”
    【解决方案3】:

    您正在为 ExcepHand 实例覆盖 toString() 方法。 You're Exception 是 ArithmeticException 的一个实例,它与你的类无关。

    要调用您自己的toString() 方法,请更改您的代码以创建ExcepHand 的新实例:

    catch(ArithmeticException e) {
        System.out.println(new ExcepHand()); // prints "Exception Occured"
        System.out.println(e); // prints "java.lang.ArithmeticException: / by zero"
    }
    

    您还可以扩展 ArithmeticException 以将您自己的消息包裹在原始 ArithmeticException 消息周围:

    public class ExcepHand extends ArithmeticException {
        private static final String messageTemplate = "Exception Occured: %s";
    
        public ExcepHand() {
            this("");
        }
    
        public ExcepHand(String s) {
            super(String.format(messageTemplate, s));
        }
    
        public static void main(String args[]) {
            int a = 10;
            int b = 0;
            try {
                int c = a / b;
            } catch (ArithmeticException e) {
                System.out.println(new ExcepHand(e.getMessage()));
            }
        }
    }
    

    这将打印:

    ExcepHand: Exception Occured: / by zero
    

    或者使用System.out.println(new ExcepHand(e.toString()));获取:

    ExcepHand: Exception Occured: java.lang.ArithmeticException: / by zero
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-25
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多