【问题标题】:How to resolve 'Define and throw a dedicated exception instead of using a generic one.' in my code如何解决“定义并抛出专用异常而不是使用通用异常”。在我的代码中
【发布时间】:2016-08-09 15:09:50
【问题描述】:
String replaceSubString(String orignal, int startIndex, int endIndex, String replaceWith){

    StringBuffer buffer = new StringBuffer(orignal);

    if ((action.getEndindex() - action.getStartindex()) < 0) {
        if (replaceWith.length() > (startIndex - endIndex)) {

                throw new RuntimeException("Replace string lenght not same as difference of start & end index.");

        }
        buffer = buffer.replace(endIndex, startIndex, replaceWith);
    } else {
        if (replaceWith.length() > (endIndex - startIndex)) {

                throw new RuntimeException("Replace string lenght not same as difference of start & end index.");

        }
        buffer = buffer.replace(startIndex, endIndex, replaceWith);
    }
    return buffer.toString();
}

嗨,这是我的代码,当我检查它的代码质量时,它显示“定义并抛出一个专用异常而不是使用通用异常”我应该怎么做才能解决这个问题?谁能帮我解决这个问题。

【问题讨论】:

  • 修复lenght的拼写。这会改善我的心情,我会发布答案。

标签: java exception-handling


【解决方案1】:

你正在抛出一个RuntimeException,它几乎是你能得到的通用的。它告诉你使用更准确地告诉你出了什么问题的东西,定义你自己的StringLengthException(或者你想命名的任何东西)然后扔掉它。

【讨论】:

  • 非常感谢您的即时回复 :-)
【解决方案2】:

您可以抛出IllegalArgumentException(因为当您的方法接收到非法参数时抛出异常)或IndexOutOfBoundsException(因为当您的方法接收索引时抛出异常,而不是抛出非常通用的RuntimeException)超出了有效范围)。

【讨论】:

  • 非常感谢您的即时回复 :-)
【解决方案3】:

代码质量要求您定义自己的异常,而不是使用预定义的 java 异常类。

所以你应该声明一个继承自RuntimeException的新类(如ReplaceStringLengthException),或者你可以抛出任何从RuntimeException派生的异常。

【讨论】:

  • 非常感谢您的即时回复 :-)
猜你喜欢
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
相关资源
最近更新 更多