Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why String.indexOf do not use exception but return -1 when substring not found?

Why String.indexOf do not use exception but return -1 when substring not found?

The purpose of this question is: when we start custom exception.

I believe avoid the need to return special error code is right design path.

What's your opinion?

like image 534
ariso Avatar asked May 13 '09 18:05

ariso


People also ask

What does the indexOf method return when the string does not contain the substring?

indexOf() returns 0 — because the substring "undefined" is found at position 0 in the string "undefined" .

What does indexOf return if found?

Returns. The zero-based index position of value from the start of the string if that character is found, or -1 if it is not.

What does lastIndexOf return if not found?

The lastIndexOf() method returns the index from the beginning (position 0). The lastIndexOf() method returns -1 if the value is not found.

Does indexOf return true?

Array Includes() and IndexOf() Methods in JavaScript This method is used to find out whether the element is included in the array or not. It returns a boolean value — true or false .


1 Answers

As a rule of thumb, if the purpose of a method is to check for something, then the lack of that something shouldn't be an exception. If the method is assuming that something is true, then the absence of that something would be an exception. Thus "File.exists()" doesn't throw a FileNotFoundException, but "File.open()" does.

like image 71
Paul Tomblin Avatar answered Sep 19 '22 11:09

Paul Tomblin