Equals方法与Throwable不兼容

Tom*_*ica 3 java error-handling equals

我有一些外部提供的回调来运行.由于它们可以包含任何内容,我更愿意冒险捕获Throwable它们,从而从可恢复的任何错误中恢复.

除非错误连续重复两次,否则允许回调执行的某些阶段抛出错误.在这种情况下,它们被标记为无效,除非用户手动启动它们,否则它们将无法再运行.

这是用于处理该方法的方法:

  /**
   * Sets whether the bot is disabled due to error or not. If error has occured during 
   * getWindow, the bot will be disabled immediatelly. If the error occured during canRun() or run()
   * the bot will only be disabled if the error is repetitive.
   * @param error error that occured
   * @param phase phase of execution in which the error occured
   * @return true if this error is not significant enough to cancel this bot
   */
  public boolean continueOnError(Throwable error, ExecutionPhase phase) {
    System.err.println("Error "+error+" caught in robot "+this.getClass().getName());
    System.err.println("Last: "+lastError+((error.equals(lastError)?" which is the same as last":" which is defferent than last")));
    if(phase == ExecutionPhase.GET_WINDOW || (error.equals(lastError) && phase==errorPhase)) {
      //Remember last
      setLastError(error, phase);
      //If robot state listener is listening, inform it about this event
      if(listener!=null)
        listener.disabledByError(error);
      //Disable the robot - on attempt to run, it will throw RobotDisabledException
      return !(errorDisabled = true);
    }
    //Rememeber last
    setLastError(error, phase);
    //The robot can remain running, but next same error will turn it down
    return true;
  }
Run Code Online (Sandbox Code Playgroud)

我知道这是一种原始的方法,但我需要从某个地方开始.此代码的问题是allways 上的equals方法Throwable返回false.查看此方法生成的输出:

Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Era*_*ran 7

Throwable不会覆盖Object's equals,所以error.equals(lastError)表现得一样error == lastError.

也许你比较这些课程就足够了:

error.getClass().equals(lastError.getClass())
Run Code Online (Sandbox Code Playgroud)

  • @TomášZato所以从不同的地方抛出相同消息的异常是不同的?这对某些人来说可能是一个惊喜.反过来对其他人来说是一个惊喜.我认为,应该总是分别抛出两个例外,因为`==`是最有意义的. (2认同)