473,569 Members | 2,522 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3331
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**@discussio ns.microsoft.co mwrote in message
news:8E******** *************** ***********@mic rosoft.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**@discussio ns.microsoft.co ma écrit dans le message de news:
8E************* *************** **...icrosof 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 #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**@discussio ns.microsoft.co mschrieb:
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**@discussio ns.microsoft.co mwrote in message
news:8E******** *************** ***********@mic rosoft.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**@discussio ns.microsoft.co mwrote in message
news:8E******** *************** ***********@mic rosoft.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.TryPars e)?

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
6025
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 containing norwegian special characters æ, ø and å. >>> liste =
4
2942
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
11954
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: print "What is the answer?" finally: print 42
7
9721
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: > > try: > x = could_raise_an_exception(23) > process(x) > except Exception, err: > deal_with_exception(err)
9
3806
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 to catch the exception and still have a finally block? This is a fictional example of what I want....
26
2492
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 Error # Error is subclass of Exception
1
1760
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 can raise an exception ...
40
3000
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 goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution...
3
2017
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 instead of a smaller set of it inside a try clause add any overhead??? 1What I'd like to understand is if, to be completely sure that no unhandles...
2
2029
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 the finally block is existing there cuz of the logic inside try block, if try is not there finally wont be there. If try and finally are so closely...
0
7701
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...
0
7615
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...
0
8130
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...
0
7979
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...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3653
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...
1
2115
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
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
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...

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.