Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve 'Define and throw a dedicated exception instead of using a generic one.' in my code

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();
}

Hi , This is my code while i check it for code quality it is showing 'Define and throw a dedicated exception instead of using a generic one" what should i do to resolve this problem? can anyone help me with that.

like image 764
minnie Avatar asked Oct 29 '22 22:10

minnie


2 Answers

You're throwing a RuntimeException which is pretty much as generic as you can get. It's telling you to use something that more accurately tells what went wrong, defining your own StringLengthException (or whatever you want to name it) and throwing that instead.

like image 51
Kayaman Avatar answered Nov 14 '22 13:11

Kayaman


Instead of throwing RuntimeException, which is quite generic, you could throw an IllegalArgumentException (since you throw your exception when your method receives illegal arguments) or IndexOutOfBoundsException (since you throw your exception when your method receives indices which are out of the valid bounds).

like image 23
Eran Avatar answered Nov 14 '22 15:11

Eran