473,403 Members | 2,359 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,403 software developers and data experts.

exceptions instead of return parameters

In one of the other threads it was mentioned that using return values
from methods to indicated success/failure of the method should be
replaced with throwing exceptions. Which would mean code like:

List l = object.Find(...);
if (l == null) ... //nothing returned

would be replaced with:

try{
List l = object.Find(...);
....
}
catch (NotFoundException ex)
{
}
catch (Exception ex)
{
}

Is this the preferred method? And what is the background on this?
dan
Apr 19 '06 #1
15 1712
It is in my opion better to have a function return a bool for success
or faliure than throwing an exception. Exceptions are resource intesive
so where possible. try something like this

public bool VerifyInitialLogin ()
{
this.emailParamater.Value = this.emailAdress;
this.passwordParamater.Value = this.password1;

//checked To see there is a password1 and email
if (String.IsNullOrEmpty(this.password1) ||
String.IsNullOrEmpty(this.emailAdress)) {
return false;
}

//Get the results back from DB
try {
this.connection.Open();
this.loginDataReader =
this.loginInfoSelectcommand.ExecuteReader();

if (this.loginDataReader.HasRows) {
this.clientID = this.loginDataReader.GetInt16(0);
this.password2 = this.loginDataReader.GetString(3);
this.firstName = this.loginDataReader.GetString(4);
this.sureName = this.loginDataReader.GetString(5);
this.companyName =
this.loginDataReader.GetString(6);
this.isFirstTime =
this.loginDataReader.GetBoolean(7);
if (!IsFirstTime) {
this.reminderQuestion =
this.loginDataReader.GetString(8);
this.reminderQuestionAnswear =
this.loginDataReader.GetString(9);
}
} else {
return false;

}
} catch (MySqlException myEX) {
throw myEX;
} finally {
this.loginDataReader.Close();
this.connection.Close();
}

return true;
}

I only throw an exception if there is some DB error not if there is
some logic error.

Apr 19 '06 #2
VJ
Throwing custom exceptions are a good habit and is how .NET is built. But
that does not mean, you don't ever return null to indicate something
failed.. Here is how I see it..

Throwing exceptions gives a detail error message of what happened in your
function, if you choose to give that out, if not you can just return null to
indicate you failed in the method by returning null

VJ
"Dan Holmes" <da*******@bigfoot.com> wrote in message
news:eR**************@TK2MSFTNGP04.phx.gbl...
In one of the other threads it was mentioned that using return values from
methods to indicated success/failure of the method should be replaced with
throwing exceptions. Which would mean code like:

List l = object.Find(...);
if (l == null) ... //nothing returned

would be replaced with:

try{
List l = object.Find(...);
...
}
catch (NotFoundException ex)
{
}
catch (Exception ex)
{
}

Is this the preferred method? And what is the background on this?
dan

Apr 19 '06 #3
Dan, I haven't read the other thread to which you refer, but I might be able
to help a bit with your question...

In my opinion, I don't think your Find method should throw a
NotFoundException. I know the definition of "failure" is subjective, but in
your example, I don't think the Find method failed to find anything; I think
it *successfully found nothing*. This may sound like it's splitting hairs,
but I do think it illustrates a key distinction.

See, I believe that exceptions should be used when a method fails to perform
its basic function for some reason. So, if the Find couldn't even begin
because a database connection wasn't available or a specified directory path
didn't exist, then an exception should be used. But if the search completed
successfully, but it just so happened that nothing was found, the method did
not fail. In a sense, the search failed, but the search *method* didn't
fail.

The condition of no results being found for a search is a normal outcome of
a Find method. In other words, it's not an exceptional result. Now, if the
search can't even start, now *that's* an exceptional situation and deserves
an exeption. Again, my rule of thumb is to limit exceptions to events that
prevent a method from performing its function, not to convey a normal result
(even if that result is negative).

- Mitchell S. Honnert
"Dan Holmes" <da*******@bigfoot.com> wrote in message
news:eR**************@TK2MSFTNGP04.phx.gbl...
In one of the other threads it was mentioned that using return values from
methods to indicated success/failure of the method should be replaced with
throwing exceptions. Which would mean code like:

List l = object.Find(...);
if (l == null) ... //nothing returned

would be replaced with:

try{
List l = object.Find(...);
...
}
catch (NotFoundException ex)
{
}
catch (Exception ex)
{
}

Is this the preferred method? And what is the background on this?
dan

Apr 19 '06 #4
Thisi s one of those religious debates. Some people believe that code is
more clear when you are returning a value to indicate success or failure.
Whether it is just true or false to indicate success or failure or any of a
bunch of values to indicate exactly what type of failure, it creates a lot of
code in any calling function.

Exceptions allow you to capture an error at whatever level you want to catch
it at without any code between where the problem occurred and where you
process it - for example if you are five function calls deep and want to
handle the error only at the highest level of the call stack - there does not
need to be any code in between. The problems with this approach are that you
generally write more code because once you start throwing exceptions you'll
generally want to start creating your own exception types (which is good but
more work). Also, less experienced coders will think that the only place
they need code is where the error is thrown and where it is caught, but you
will also need error handling in between anywhere you might have alocated any
resources that would need to be dealocated.

Overall, I personally like throwing exceptions, but there is not "one right
way". There's really not even a good concensus.
"Dan Holmes" wrote:
In one of the other threads it was mentioned that using return values
from methods to indicated success/failure of the method should be
replaced with throwing exceptions. Which would mean code like:

List l = object.Find(...);
if (l == null) ... //nothing returned

would be replaced with:

try{
List l = object.Find(...);
....
}
catch (NotFoundException ex)
{
}
catch (Exception ex)
{
}

Is this the preferred method? And what is the background on this?
dan

Apr 19 '06 #5
Dan,
A "Not found" condition in a search method is a common and expected business
logic condition, therefore it does not fit the purpose of what exceptions are
for.

Exceptions should be used for really exceptional conditions such as failed
database connection, or the collection itself is null so no search can even
be made.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Dan Holmes" wrote:
In one of the other threads it was mentioned that using return values
from methods to indicated success/failure of the method should be
replaced with throwing exceptions. Which would mean code like:

List l = object.Find(...);
if (l == null) ... //nothing returned

would be replaced with:

try{
List l = object.Find(...);
....
}
catch (NotFoundException ex)
{
}
catch (Exception ex)
{
}

Is this the preferred method? And what is the background on this?
dan

Apr 19 '06 #6

"Mitchell S. Honnert" <ne**@REMhonnertOVE.com> wrote in message
news:uE**************@TK2MSFTNGP04.phx.gbl...
Dan, I haven't read the other thread to which you refer, but I might be
able to help a bit with your question...

In my opinion, I don't think your Find method should throw a
NotFoundException. I know the definition of "failure" is subjective, but
in your example, I don't think the Find method failed to find anything; I
think it *successfully found nothing*. This may sound like it's splitting
hairs, but I do think it illustrates a key distinction.


IMHO a method is called "Find" for one of two reasons:

1) It expects to fail to find the thing sometimes and hence it is not an
abnormal condition and no exception should be thrown.

2) It is not expected to fail to get the object but is stupidly exposing the
implementation detail that a search is involved. In this case it should have
been called "Get".
Apr 19 '06 #7

"Jeffrey Hornby" <Je***********@discussions.microsoft.com> wrote in message
news:A5**********************************@microsof t.com...
Thisi s one of those religious debates. Some people believe that code is
more clear when you are returning a value to indicate success or failure.
Whether it is just true or false to indicate success or failure or any of
a
bunch of values to indicate exactly what type of failure, it creates a lot
of
code in any calling function.

Exceptions allow you to capture an error at whatever level you want to
catch
it at without any code between where the problem occurred and where you
process it - for example if you are five function calls deep and want to
handle the error only at the highest level of the call stack - there does
not
need to be any code in between.


It is incorrect and unhelpful to throw low level exceptions from high level
methods. This usually rules out catching anything like a NotFoundException
from some sort of collection class much above the throw point. Of course you
can catch Exception but only to do something general with it. For example -
if you were to call something like form.ShowDialog() and you got a
NotFoundException you wouldn't know what to do with it which is why methods
such as this do not allow low level exceptions to propagate.
Apr 19 '06 #8
"bombdrop" <sr********@yahoo.co.uk> wrote in message
news:11*********************@e56g2000cwe.googlegro ups.com...
I only throw an exception if there is some DB error not if there is
some logic error.


So, if something other than a database error occurs, you don't even care...?
Apr 19 '06 #9
Several of the posts so far argue from the point of view that you are
the writer of all of the code, and so can decide what constitutes an
"exceptional" situation from the point of view of the caller, and what
doesn't.

If that's the case, then exception-versus-return-value is an easy
decision: is it something that your caller is expecting might happen?
Then it's not an exception.

When you're writing a library for future use, however, the waters
become muddier. I wouldn't call it a "religious debate." Rather, I
would call it lack of information about who is going to use your method
and for what. When you don't know who your callers will be, you just
have to make a guess at what is an "exceptional" situation and what is
not. Different people posting here have had different opinions on how
to decide.

You may notice that even in the .NET Framework, sometimes a designer
realizes that the original decision was not the right one. In .NET 1.1,
most primitive types just had a Parse method that threw an exception if
the input string was of the wrong format. Now, in .NET 2.0, we have
TryParse. The original designers decided that "wrong format" was an
exceptional situation, then after seeing how people used the methods,
they decided that "wrong format" was sufficiently common that there
needs to be a way to test it without resorting to exceptions.

The only general rule I would put forth would be that if you expect
your callers to be testing for something a lot, you should offer them a
return value (or another method like TryParse) rather than forcing them
to put try...catch everywhere. try...catch should be an uncommon
construct in client programs, not because "it's slow" (it's not,
terribly), but because it interrupts normal control flow and makes the
code difficult to follow.

Apr 19 '06 #10
bombdrop <sr********@yahoo.co.uk> wrote:
It is in my opion better to have a function return a bool for success
or faliure than throwing an exception. Exceptions are resource intesive
so where possible. try something like this


Just out of interest (and before following the link below) - just how
resource intensive do you think exceptions are? How many exceptions do
you think you could throw per second? How often would you have to throw
them in order to actually see significant performance loss?

A ValidateLogin method probably *should* return a boolean, because its
whole purpose is to verify data. The username and password being
incorrect isn't a failure situation - it's perfectly normal. Any other
error, however - whether database-related or not - should result in
exceptions, IMO.

See http://www.pobox.com/~skeet/csharp/exceptions.html for more on
this.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 19 '06 #11
Bruce Wood <br*******@canada.com> wrote:

<snip>
The only general rule I would put forth would be that if you expect
your callers to be testing for something a lot, you should offer them a
return value (or another method like TryParse) rather than forcing them
to put try...catch everywhere. try...catch should be an uncommon
construct in client programs, not because "it's slow" (it's not,
terribly), but because it interrupts normal control flow and makes the
code difficult to follow.


Spot on. I couldn't have (and plainly haven't!) said it better myself.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 19 '06 #12
Great post Dan, I've been meaning to blog on this for a while, so
here's my tuppence.

http://www.thejoyofcode.com/Exceptions.aspx

Apr 19 '06 #13
He's trying to return an object from his find method, not a bool on
whether it's found or not. He needs an "exists" type method on this
class but I definitely think the find method needs to throw an
exception similar to an IndexOutOfRange exception with arrays.
Otherwise there's no way to differientiate between an existing null
item and a non-existent item.

Apr 19 '06 #14
Hey wfairl,

I see your point - but my blog entry isn't a direct answer to this post
but a general steam off on the subject.

IMO it all comes back to that implicit assumptions definition I quoted
from Richter.

Your proposition is only valid if there is someway that the things you
are looking for with the Find thing could actually be null, which would
be unusual. The nearest example I can think of is ASP.NET's FindControl
method, this returns null if nothing is found, but then you can't add
Null to the controls collection so that makes sense.

Hopefully Dan's got enough AMMO now to go on and make an informed
decision using his greater knowledge of the requirement and audience.

I beginning to think a *consistent* approach to this particular issue
might be best i.e. always throwing exceptions, but also always provide
a TryGetValue for developers ready to deal with the possibility of a
null return... food for thought anyway. T

Apr 19 '06 #15

<wf****@gmail.com> wrote in message
news:11**********************@v46g2000cwv.googlegr oups.com...
He's trying to return an object from his find method, not a bool on
whether it's found or not. He needs an "exists" type method on this
class but I definitely think the find method needs to throw an
exception similar to an IndexOutOfRange exception with arrays.
Otherwise there's no way to differientiate between an existing null
item and a non-existent item.


There is always "bool Find(object key,out object value)" .
This is probably the most logically correct but unappealing approach.
Apr 20 '06 #16

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

Similar topics

33
by: Steven Bethard | last post by:
I feel like this has probably been answered before, but I couldn't find something quite like it in the archives. Feel free to point me somewhere if you know where this has already been answered. ...
5
by: John | last post by:
Hi, In my years as a VB programmer, I have settled into this pattern of creating collections classes, with an AddNew() method. AddNew() validates the parameters, instantiates the object, adds...
59
by: kk_oop | last post by:
Hi. I wanted to use exceptions to handle error conditions in my code. I think doing that is useful, as it helps to separate "go" paths from error paths. However, a coding guideline has been...
1
by: N.V.Dev | last post by:
Hi, I have written an ESQL/C program and should any error occur; the same should be displayed as error message. Wrote a test script and expected an exception but DB2 did not throw any such...
15
by: Bernard | last post by:
Hi All, I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions...
1
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I...
11
by: Jonathan Wood | last post by:
I must be the only one who doesn't think exceptions are the greatest thing since bread. Consider the following code: id = Convert.ToInt32(Request.QueryString); First, is there an easy way...
13
by: mike3 | last post by:
Hi. (crossposted because the program is in C++ and some C++-related elements are discussed, hence comp.lang.c++, plus general program design questions are asked, hence comp.programming.) I'm...
17
by: Christoph Zwerschke | last post by:
I'm just reading PEP 3107 (function annotations) and wonder why exceptions are not mentioned there. I think it would be helpful if one could specify which exceptions can be raised by a function,...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...
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
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...
0
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...

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.