【问题标题】:Custom exception in Java with external message带有外部消息的 Java 中的自定义异常
【发布时间】:2022-01-05 11:47:53
【问题描述】:

我们刚从大学 Java 中的异常开始,我在这个任务上坐了很长时间,但我仍然无法走得更远。

任务是根据构造函数中的参数自定义带有消息的异常。我的想法是为消息编写一个额外的方法,但我很难访问参数中的变量

这是我目前所拥有的

import java.util.Calendar;

public class BadUpdateTimeException extends Exception{

    private final boolean b;
    private final Calendar cal;
    
    public BadUpdateTimeException(Calendar cal, boolean b) {
        super(message());
        this.b = b;
        this.cal = cal;
    }
    
    private static String message() {
        if(b == true) {
            String s = "Update time is earlier than the last update: ";
            return s;
        }else {
            String s = "Update time is in the future: ";
            return s;
        }
    }
} 

【问题讨论】:

  • static 阻止您访问实例字段,请将其删除。但是在这种情况下,由于执行顺序,您应该将b作为参数传递给message
  • 但是如果我这样做了,我就无法在super中访问它了
  • 但是如果我删除静态,super 中的消息将不再像我的编译器所说的那样工作。

标签: java exception


【解决方案1】:

这里的问题是你正在调用超类的构造函数,这必须在其他任何事情之前完成。

因此,您无法在 message 方法中访问诸如 b 之类的字段,因为它们尚未设置。

将构造函数的第一行更改为

super(message(b));

message 方法

private static String message(boolean b) 

这将使消息方法与稍后将分配给类字段的值的本地副本一起使用。

【讨论】:

  • 哇,感谢您的快速和乐于助人的回复!现在明白了!:)
  • 你可以投票和/或接受这个答案:)
【解决方案2】:

首先,你不应该在静态方法中使用类的参数;您必须通过方法的参数委托它。然后你会得到一个非常有效的解决方案。

public class BadUpdateTimeException extends Exception{

    public BadUpdateTimeException(Calendar cal, boolean b) {
        super(createMessage(cal, b));
    }
    
    private static String createMessage(Calendar cal, boolean b) {
        if (b)
            return "Update time is earlier than the last update: ";
        
        return "Update time is in the future: ";
    }
}

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2017-02-28
    • 2023-03-05
    • 2015-11-04
    • 2012-01-17
    相关资源
    最近更新 更多