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?
indexOf() returns 0 — because the substring "undefined" is found at position 0 in the string "undefined" .
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.
The lastIndexOf() method returns the index from the beginning (position 0). The lastIndexOf() method returns -1 if the value is not found.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With