Use Try-Catch or If Statement?

G

Guest

Hi. I have a class with an collection property. The collection property is
sometimes equal to nothing. The class has a function named 'Exists' which
returns TRUE if the specified string exists in the collection, and FALSE if
it does not. This is illustrated below.

My co-worker and I are having a friendly disagreement as to whether or not
we should rely on an exception to return a result. My coworker's version of
the function and mine are shown below. As you can see, they are both having
the same logic, but one is using a try-catch (relying on the catch to return
FALSE), and the other uses an IF statement.

Is one of these functions necessarily better than the other? Is my
coworker's function better than mine or vica vera? Are there any performance
benefits of using try-catch versus if-endif?

Thanks.
-----------------------------------------------------------
Public Class MyClass
Protected _Col As Collection

'************************************************************
' MY COWORKER'S FUNCTION

Public Function Exists(ByRef sKey As String) As Boolean
Try
If Not _Col.Item(sKey) Is Nothing Then Return True
Catch 'sometimes _Col=Nothing, hence the try-catch
Return False
End Try
End Function
'************************************************************

'************************************************************
' MY FUNCTION

Public Function Exists(ByRef sKey As String) As Boolean
Dim bReturn as Boolean = False

If Not _Col Is Nothing AndAlso _
Not _Col.Item(skey) is Nothing Then
bReturn = True
End If

Return bReturn
End Function
'************************************************************
End Class
 
O

\(O\)enone

Mike said:
Is one of these functions necessarily better than the other? Is my
coworker's function better than mine or vica vera? Are there any
performance benefits of using try-catch versus if-endif?

Your version is better. There's a substantial overhead to throwing an
exception, which your version avoids by pre-empting and avoiding the problem
in the first place.

Also, what happens if a different problem occurs in your co-worker's
example? The exception will be swallowed up and ignored, whereas your
version would correctly report the error further up the call stack.

HTH,
 
E

Eric Turvey

You should never rely on try-catch to purposly create an error.
There is a performance issue associated with this error handling routine
and thus it should only be used for unintentional errors. It also
does not clearly represent the coders inrentions to other people reading
your code.
 
G

Guest

Thank you for responding!

(O)enone said:
Your version is better. There's a substantial overhead to throwing an
exception, which your version avoids by pre-empting and avoiding the problem
in the first place.

Also, what happens if a different problem occurs in your co-worker's
example? The exception will be swallowed up and ignored, whereas your
version would correctly report the error further up the call stack.

HTH,
 
J

José Joye

IMO, try-catch statements are to be used to handle exceptional cases and not
to simulate a kind of if-then-else statement.
In your case, this is not an exceptional case, you just expect from time to
time this situation.

Also keep in mind, that entering in a catch statement has a performance
penalty (wich is more than acceptable in case your are really catching an
error). In this case, for instance, the error object is constructed.

- José


Also remember that
 
C

Chris Anderson

Hello Mike,
In this case, I'd go for the IF statement.
The why is simple. Error handling is for dealing with the unknown or unaccountable
when it happens. In this case, it's known that this could happen. Therefore,
it should be treated and accounted for accordingly. It's a known state. Even
if it's a least likely situation.
Second reason, exceptions are excepensive, and even with today's processors,
anything that can be done to speed things up (users are quite the impatient
types) is a good thing.

FYI - I'd expand the checking a little further to also check to see if your
collection .Contains the key before trying to access it.


Chris Anderson VB-MVP
 
H

Herfried K. Wagner [MVP]

Mike said:
Hi. I have a class with an collection property. The collection property
is
sometimes equal to nothing. The class has a function named 'Exists' which
returns TRUE if the specified string exists in the collection, and FALSE
if
it does not. This is illustrated below.

My co-worker and I are having a friendly disagreement as to whether or not
we should rely on an exception to return a result. My coworker's version
of
the function and mine are shown below. As you can see, they are both
having
the same logic, but one is using a try-catch (relying on the catch to
return
FALSE), and the other uses an IF statement.

Is one of these functions necessarily better than the other? Is my
coworker's function better than mine or vica vera? Are there any
performance
benefits of using try-catch versus if-endif?

-----------------------------------------------------------
Public Class MyClass
Protected _Col As Collection

'************************************************************
' MY COWORKER'S FUNCTION

Public Function Exists(ByRef sKey As String) As Boolean

First of all, I'd pass 'sKey' 'ByVal' instead of 'ByRef'!
Try
If Not _Col.Item(sKey) Is Nothing Then Return True
Catch 'sometimes _Col=Nothing, hence the try-catch
Return False
End Try
End Function
'************************************************************

'************************************************************
' MY FUNCTION

Public Function Exists(ByRef sKey As String) As Boolean
Dim bReturn as Boolean = False

If Not _Col Is Nothing AndAlso _
Not _Col.Item(skey) is Nothing Then
bReturn = True
End If

Return bReturn
End Function
'************************************************************
End Class

In this particular situation I would prefer your version.
 
C

Chris Mullins [MVP]

I'm not really a big fan of either version, but if I had to pick, I would go
with yours.

The reason being is that Exceptions shouldn't be used as flow control, as it
adds quite a bit of complexity. It also makes debugging harder (try running
with "Break on all Exceptions" set to true!), and is likley to be screwed up
by someone somewhere down the line. There's also a performance penalty, but
the clarity argument is really more compelling.

Is there a reason you can't use .Contains? This is exposed by the IList
interface, and should be available.

Also, most of the more advanced datastructures (like Dictionary) expose a
TryGet() method that really offers the best of both.
 
H

Hal Rosser

Mike said:
Hi. I have a class with an collection property. The collection property
is
sometimes equal to nothing. The class has a function named 'Exists' which
returns TRUE if the specified string exists in the collection, and FALSE
if
it does not. This is illustrated below.

My co-worker and I are having a friendly disagreement as to whether or not
we should rely on an exception to return a result. My coworker's version
of
the function and mine are shown below. As you can see, they are both
having
the same logic, but one is using a try-catch (relying on the catch to
return
FALSE), and the other uses an IF statement.

Is one of these functions necessarily better than the other? Is my
coworker's function better than mine or vica vera? Are there any
performance
benefits of using try-catch versus if-endif?

Thanks.
-----------------------------------------------------------
Public Class MyClass
Protected _Col As Collection

'************************************************************
' MY COWORKER'S FUNCTION

Public Function Exists(ByRef sKey As String) As Boolean
Try
If Not _Col.Item(sKey) Is Nothing Then Return True
Catch 'sometimes _Col=Nothing, hence the try-catch
Return False
End Try
End Function
'************************************************************

'************************************************************
' MY FUNCTION

Public Function Exists(ByRef sKey As String) As Boolean
Dim bReturn as Boolean = False

If Not _Col Is Nothing AndAlso _
Not _Col.Item(skey) is Nothing Then
bReturn = True
End If

Return bReturn
End Function
'************************************************************
End Class

In this particular case, the IF statement wins because of the overhead
associated with generating an Exception object. Rule of thumb is to use If
statements if you can, over Try-Catch.
However (IMHO) If you had a method which HAS to be run in a Try block - or
'throw' the exception, then why not go ahead and use it. (I may be Thinking
in Java here).
 
P

Phill W.

Mike said:
Is one of these functions necessarily better than the other? Is my
coworker's function better than mine or vica vera? Are there any performance
benefits of using try-catch versus if-endif?

Put these tests into a tight loop and you'll /very/ soon see the
difference in timings (and CPU load!!).

Exceptions are heavy-weight things to be throwing around - no pun
intended - and /aren't/ suitable for detecting the presence or absence
of things that you can realistically /expect/ to be missing as the code
runs.
If your database disappears halfway through a run, though, /that's/
Exception time.

(Your colleague may be reliving the Collection techniques used in VB
"Proper", where the /only/ way to detect a missing item in a Collection
was to try to read it and catch the error).

This discrepancy - "If" vs. "Catch" - must have occurred to Our Friends
in Redmond as well - why else did the Try* methods appear in Framework
2.0 (e.g. Integer.TryParse)?

HTH,
Phill W.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top