473,406 Members | 2,849 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Use Try-Catch or If Statement?

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
May 31 '07 #1
9 3321
Mike wrote:
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,

--

(O)enone
May 31 '07 #2
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.
"Mike" <Mi**@discussions.microsoft.comwrote in message
news:8E**********************************@microsof t.com...
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

May 31 '07 #3
Thank you for responding!

"(O)enone" wrote:
Mike wrote:
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,

--

(O)enone
May 31 '07 #4
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

"Mike" <Mi**@discussions.microsoft.coma écrit dans le message de news:
8E**********************************@microsoft.com...
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

May 31 '07 #5
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

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

May 31 '07 #6
"Mike" <Mi**@discussions.microsoft.comschrieb:
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.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

May 31 '07 #7
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.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

"Mike" <Mi**@discussions.microsoft.comwrote in message
news:8E**********************************@microsof t.com...
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

May 31 '07 #8

"Mike" <Mi**@discussions.microsoft.comwrote in message
news:8E**********************************@microsof t.com...
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).
Jun 1 '07 #9
Mike wrote:
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.
Jun 1 '07 #10

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

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
4
by: Brian Alexander | last post by:
Hello; I'm curious to know how people preserve exceptions that arise in a try ... finally block. Consider this example: try: getResource() doSomething() finally: alwaysFreeResource()
13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
9
by: David Stockwell | last post by:
In referring to my copy of the python bible, it tells me I can't use all three items 'try' except and finally. I can use the t/f or t/e combinations though What combination can i use if i want...
26
by: djw | last post by:
Hi, Folks- I have a question regarding the "proper" use of try: finally:... Consider some code like this: d = Device.open() try: d.someMethodThatCanRaiseError(...) if SomeCondition: raise...
1
by: djw | last post by:
c.l.p- I am having trouble understanding how one is supposed to correctly utilize try:...except:...finally: in real code. If I have a block of code like: def foo(): try: ... some code that...
40
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the...
3
by: Bob Rock | last post by:
Hello, this is something I've been asking myself for sometime ... and now I'd like to clarify this point. When should the try block start in a method??? What I mean is, does having all the code...
2
by: Abubakar | last post by:
Hi all, The variables declared inside try block cant be accessed inside its corresponding finally block. When I used to explain finally concept to anyone I would usually tell them (briefly) that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.