473,664 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why does IndexOf still return -1

Wouldn't it make sense if IndexOf just threw a character not found
exception instead of -1?

If -1 is what you were expecting there should be a function ContainsChar
that returns bool.

Thoughts?

Mar 29 '06 #1
25 2588
what's the difference between a known exception and a known return based
on the same input data? your logic to handle the error would very
likely be the same...

personally, as long as i know what happens when i give a particular
function some data, i don't care how it handles something like that. it
could return -3.14159 or throw a YoureAFoolForTr yingThatExcepti on, as
long as its in the documentation.

Gordon Cowie wrote:
Wouldn't it make sense if IndexOf just threw a character not found
exception instead of -1?

If -1 is what you were expecting there should be a function ContainsChar
that returns bool.

Thoughts?

Mar 29 '06 #2
jeremiah johnson wrote:
what's the difference between a known exception and a known return based
on the same input data? your logic to handle the error would very
likely be the same...

personally, as long as i know what happens when i give a particular
function some data, i don't care how it handles something like that. it
could return -3.14159 or throw a YoureAFoolForTr yingThatExcepti on, as
long as its in the documentation.


It would be "cleaner" as far as separation of the error-handling type of
code goes. Take, for example this function.

int a = SomeString.Inde xOf("f");
if (a != -1)
{
int b = SomeString.Inde xOf("g");
if (b != -1)
{
int c = SomeString.Subs tring(a,b).Inde xOf("i");
if (c != -1)
{
return(SomeStri ng.Substring(0, c);
}
else
throw InvalidStuff;
}
else
throw InvalidStuff;
}
else
throw InvalidStuff;

phew. now, with exceptions..

try
{
return Somestring.Subs tring(0,
SomeString.Subs tring(
SomeString.Inde xOf("f"),
SomeString.Inde xOf("g")).Index Of("i"));
}
catch(CharNotFo undException e)
{
throw InvalidStuff;
}

cleaner no? no pesky a,b,c variables either.
Mar 29 '06 #3
It would be "cleaner" as far as separation of the error-handling type of
code goes.
But it's not necessarily an error if the string doesn't contain the
specified character.

try
{
return Somestring.Subs tring(0,
SomeString.Subs tring(
SomeString.Inde xOf("f"),
SomeString.Inde xOf("g")).Index Of("i"));
}
catch(CharNotF oundException e)
{
throw InvalidStuff;
}


You can still do it this way, Substring shouold throw if you end up
passing -1 to it.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 29 '06 #4

"Gordon Cowie" <go***@dynamics direct.com> wrote in message
news:%2******** *******@TK2MSFT NGP11.phx.gbl.. .
jeremiah johnson wrote: try
{
return Somestring.Subs tring(0,
SomeString.Subs tring(
SomeString.Inde xOf("f"),
SomeString.Inde xOf("g")).Index Of("i"));
}
catch(CharNotFo undException e)
{
throw InvalidStuff;
}

cleaner no? no pesky a,b,c variables either.


Sure, as long as you want to call SubString a bunch if times and throw away
the values :)

I prefer the -1 in this case much more. An exception should be used (IMHO)
for "exceptiona l" circumstances - IndexOf not finding a character is a
"normal" outcome for IndexOf. An execption would be useful if the target
string was null (as it does throw), or if c# strings were kept in native
encodings and they didn't match, etc. Another case is when no "out of band"
sentinal value is possible -- like "int GetNextInt()". Although it's a
matter of taste in most cases, I reckon...
Mar 29 '06 #5
It would also be far more expensive. Exceptions are very expensive and
really, exceptions are for "exceptiona l" events, things that you normally
would not have control over.

For instance, if you open a socket and the network suddenly shutdown, well,
that is not something your app could have predicted.

"Gordon Cowie" <go***@dynamics direct.com> wrote in message
news:%2******** *******@TK2MSFT NGP11.phx.gbl.. .
jeremiah johnson wrote:
what's the difference between a known exception and a known return based
on the same input data? your logic to handle the error would very likely
be the same...

personally, as long as i know what happens when i give a particular
function some data, i don't care how it handles something like that. it
could return -3.14159 or throw a YoureAFoolForTr yingThatExcepti on, as
long as its in the documentation.


It would be "cleaner" as far as separation of the error-handling type of
code goes. Take, for example this function.

int a = SomeString.Inde xOf("f");
if (a != -1)
{
int b = SomeString.Inde xOf("g");
if (b != -1)
{
int c = SomeString.Subs tring(a,b).Inde xOf("i");
if (c != -1)
{
return(SomeStri ng.Substring(0, c);
}
else
throw InvalidStuff;
}
else
throw InvalidStuff;
}
else
throw InvalidStuff;

phew. now, with exceptions..

try
{
return Somestring.Subs tring(0,
SomeString.Subs tring(
SomeString.Inde xOf("f"),
SomeString.Inde xOf("g")).Index Of("i"));
}
catch(CharNotFo undException e)
{
throw InvalidStuff;
}

cleaner no? no pesky a,b,c variables either.

Mar 29 '06 #6

"Gordon Cowie" <go***@dynamics direct.com> wrote in message
news:uS******** ******@TK2MSFTN GP09.phx.gbl...
Wouldn't it make sense if IndexOf just threw a character not found
exception instead of -1?
Not necessarily. In many cases it isn't exceptional.
The real answer is an overload with an extra boolean parameter to indicate
whether you want an exception (You could use a different named method
instead but that would clutter the docs and intellisense more)
If -1 is what you were expecting there should be a function ContainsChar
that returns bool.


No because then if you need the index if it is there but it is optional (a
common case) then you must either incur the exception cost or incur the
search cost twice.

Another reason not to throw exception unless something bad has happened is
that it makes debugging harder - typically when I have a problem I would
tell the debugger to stop on exceptions - If there is one for an
unexceptional case then you need separate exception types and you need to
mess around with telling it which ones to stop for and which not and then
just maybe it really is the source ofthe problem one time. If you use the -1
incorrectly it will usually turn up as an array bounds exception.
Mar 29 '06 #7
Peter Rilling <pe***@nospam.r illing.net> wrote:
It would also be far more expensive. Exceptions are very expensive and
really, exceptions are for "exceptiona l" events, things that you normally
would not have control over.


Exceptions aren't nearly as expensive as most people think. See
http://www.pobox.com/~skeet/csharp/exceptions.html
(In this particular case the performance penalty could be significant
in many programs, but I don't want you follow the myth of exception
performance :)

However, they're still wrong in this situation, because it really isn't
exceptional for a character not to be present in a string - it's
something which is almost always a possibility when you use IndexOf, in
my experience. It's rarely an error condition which would make you want
to unwind the stack a significant distance.

Of course, if Gordon wants to write his own method which throws an
exception instead of returning -1, there's nothing to stop him -
whereas if the method already threw an exception, wrapping it in a
method which returned -1 would incur the performance penalty of the
exception.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 29 '06 #8
Jon,

Note that Exceptions are significantly more expensive in V2, as shown here:

V1.1
Total time taken: 00:00:32.276803 3
Exceptions per millisecond: 154

V2
Total time taken: 00:02:59.315769 6
Exceptions per millisecond: 27

that means 37 µsecs. per exception, I would say this is more expensive as
some people think ;-)

Willy.
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
| Peter Rilling <pe***@nospam.r illing.net> wrote:
| > It would also be far more expensive. Exceptions are very expensive and
| > really, exceptions are for "exceptiona l" events, things that you
normally
| > would not have control over.
|
| Exceptions aren't nearly as expensive as most people think. See
| http://www.pobox.com/~skeet/csharp/exceptions.html
| (In this particular case the performance penalty could be significant
| in many programs, but I don't want you follow the myth of exception
| performance :)
|
| However, they're still wrong in this situation, because it really isn't
| exceptional for a character not to be present in a string - it's
| something which is almost always a possibility when you use IndexOf, in
| my experience. It's rarely an error condition which would make you want
| to unwind the stack a significant distance.
|
| Of course, if Gordon wants to write his own method which throws an
| exception instead of returning -1, there's nothing to stop him -
| whereas if the method already threw an exception, wrapping it in a
| method which returned -1 would incur the performance penalty of the
| exception.
|
| --
| Jon Skeet - <sk***@pobox.co m>
| http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
| If replying to the group, please do not mail me too
Mar 29 '06 #9
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
Note that Exceptions are significantly more expensive in V2, as shown here:

V1.1
Total time taken: 00:00:32.276803 3
Exceptions per millisecond: 154

V2
Total time taken: 00:02:59.315769 6
Exceptions per millisecond: 27

that means 37 µsecs. per exception, I would say this is more expensive as
some people think ;-)


It's much less expensive than some people think though. There was a
thread on one of the groups a while ago where people were blaming poor
web app performance on the fact that it threw 200 exceptions *per
hour*.

In situations where exceptions are logical to use in the first place
(where usually several levels of stack will be unwound) 37 microseconds
is completely insignificant.

Having said all that, it's surprising just how much slower they are in
2.0...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 29 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1997
by: John | last post by:
The following code works OK in IE 6.0 but does not work in Netscape 7. The image does not shift when one scrolls down but stays stationary in Netscape. Please help Thank you John function moveImage(e){ //shift image according to scroll
0
1191
by: Phadnis | last post by:
hi. i have set up a proxy server which gets the text content but does not get the images. wat additional code i need to rite for this.. also this code works with only simple website that does not store cookies.. so any suggestions on how to work with sites like rediff n yahoo.. plz help on images first.. n later on for the other problem Public Sub New(ByVal socket As Socket) Me.clientSocket = socket
4
7287
by: Reena | last post by:
Hi, code from .aspx page... using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web;
2
3304
by: Bernard Bourée | last post by:
I have a class named "Variable" with 2 properties "Name" and "Value" and the following class to handle a collection of Variable: Public Class ColVariables Inherits CollectionBase Default Public Property Item(ByVal index As Integer) As Variable Get Return CType(List(index), Variable) End Get Set(ByVal Value As Variable)
18
4730
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
1
9477
by: kamleshsharmadts | last post by:
I am using Ajax with struts in web application. from jsp i am calling a function of ajax.js onclick of a button. code of that call function which calling from jsp given as below:- onclick="retrieveURL('/application/home_page.do?processAction=ItinerarySearch','AfoHomeForm')" after clicking on button i am getting following error:- object does not support this property or method at statement (Which i have made it bold in js file)
1
3849
by: smilecry | last post by:
I am trying to create a tree table (javascript code was adopted from online source) but the rowspan in td tag does not work well when I toggle the rows. Here is the sample code, notice the row "4" should be in the Type 1 section (click on the arrow and expand it, it will display correctly), but when it is collapsed, it is pushed downwards to Type 2 section. Could not figure out what is the reason. Any ideas? Thanks! <html> <head>
1
8365
Atli
by: Atli | last post by:
The following small HowTo is a compilation of an original problem in getting some cookie-values through different methods of string-handling. The original Problem was posted as follows: As you can see, there could have been a problem with the split-method. The following short article handles ways around this possible problem, that we couldn't reproduce, but someone may possibly encounter it too sometimes. If nothing else, the shown...
3
3232
by: nma | last post by:
Hi This code goes well with play, stop and fullscreen button, the only thing is the pause button is not there. How to make pause button? I try to make pause button but when it streams video, when I click pause, it stop but it work play again when i click at play button. Please help. <?php function printInstructions() { ?>
0
8438
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8779
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7376
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4186
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4356
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1761
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.