Exception vs Boolean

G

Guest

Which approach is better:
1) Use a method that returns true/false (the method will log the exception
that lead to false using log4net for example)
OR
2) Use a method that returns void and throws an exception in case of failure?

If the second approach is to be suggested: Should .NET predefined
exceptions, NullReferenceException, IndexOutOfRangeException and so on, or my
own exceptions be thrown?

Thanks in advance,
Shehab.
 
S

Siva M

From the horse mouth:
http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx

Which approach is better:
1) Use a method that returns true/false (the method will log the exception
that lead to false using log4net for example)
OR
2) Use a method that returns void and throws an exception in case of
failure?

If the second approach is to be suggested: Should .NET predefined
exceptions, NullReferenceException, IndexOutOfRangeException and so on, or
my
own exceptions be thrown?

Thanks in advance,
Shehab.
 
G

Guest

I'm really convinced that I should throw my own custom exceptions but the
article sates that "Do not create and throw new exceptions just to have ‘your
team's’ exception".
Do you have more resources about throwing custom exceptions? When and when
not to use them?

Thanks in advance,
Shehab.
 
S

Scott M.

Exceptions are expensive in terms of CLR performance and so, you should
avoid throwing them when you can.

If you decide that an exception is what you need, you can certainly use the
built-in exception types if they fit your situation or you can certainly
create a custom exception based on one of the built-in exception classes.
 
S

Scott M.

I think that article sums it up quite nicely:

Do not use exceptions for normal execution flow.
Do use exeptions for system failures.
 
S

Siva M

Custom exceptions are generally useful for indicating businesss-specific
error conditions. For example, if a request is made to create a Customer
object with an invalid customer ID, you could raise a custom exception, say
CustomerNotFound exception which could in turn be caught and handled by the
calling layer. However, .NET Framework already comes with many exception
types and make sure none of them fit your case before proceeding with
creating your own.

Take a look at this (& the sub-topics) anyway:
http://msdn2.microsoft.com/en-us/library/ms229014.aspx


I'm really convinced that I should throw my own custom exceptions but the
article sates that "Do not create and throw new exceptions just to have
‘your
team's’ exception".
Do you have more resources about throwing custom exceptions? When and when
not to use them?

Thanks in advance,
Shehab.
 
B

Barry Kelly

Shehab Kamal said:
I'm really convinced that I should throw my own custom exceptions but the
article sates that "Do not create and throw new exceptions just to have ‘your
team's’ exception".
Do you have more resources about throwing custom exceptions? When and when
not to use them?

If code calling your methods can have meaningful behaviour based on the
exception type, then it makes sense to throw a particular exception
type. For example, when downloading a file, the errors 'host not found'
and 'timeout occurred on connect' are different and the program can take
different behaviours for them. For a timeout, it can retry - but if the
host isn't found, it's unlikely to be found with a retry. Thus, there
should be a different exception thrown for the two cases.

-- Barry
 
B

Barry Kelly

Scott M. said:
Exceptions are expensive in terms of CLR performance and so, you should
avoid throwing them when you can.

I'd advise measuring before taking drastic action to remove them from
your code. Propagating meaningful error information up the stack is more
expensive in pretty much every way than exceptions: more code to
maintain, more rigorous coding standard required, every called function
needs to propagate the return value, need to convert properties into
methods so that a separate return value can be used for the error, can't
write simple expressions like 'a.Prop1 + b.Prop2' because properties
turn into methods with 'out' parameters, etc.

I would strongly prefer exceptions to error codes unless it's easy to
use a semantic two-way (i.e. test and perform) operation instead, like
int.TryParse and Dictionary<TKey,TValue>.TryGetValue. These are best
suited to 'leaf' operations, operations that don't go off and call some
deep graph of other methods.

-- Barry
 
J

Jon Skeet [C# MVP]

Scott M. said:
Exceptions are expensive in terms of CLR performance and so, you should
avoid throwing them when you can.

You can *always* avoid throwing them though - your advice, taken
literally, translates to "Never throw exceptions". Consider what would
have happened if the framework designers had followed your advice for
FileStreams. If a file didn't exist when you asked to open it, you
could get a "null stream" which silently returned no data. You could
then check a property to see whether everything was okay or not. That
would avoid throwing exceptions - but would have been *terribly* for
robustness.

Yes, exceptions are expensive compared with a normal return - but if
used properly, they should indicate an error situation which means that
performance is likely to be unimportant at that point. If you have a
tight loop which throws thousands of exceptions then at *that* point
exceptions will make a significant difference - but then the situation
isn't exceptional.

The performance penalty of exceptions has been hugely overstated, I
believe mostly because it's so large for the first exception thrown
when debugging.

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

Scott M.

No Jon, my advice taken literally is exactly what I said "you should avoid
them when you can". Your interpretation of that was "don't use them because
tyhey can always be avoided".

But, obviously (as you point out) avoiding an exception could cause other
problems down the line. In my opinion, that would fall into the "I guess I
need this exception and shouldn't avoid it" camp.

My advice was based on the OP, return a value vs. throw an exception. The
point was don't just throw an exception because you can. Also, if you see
my other comment in the branch thread, you'll see I qualify my point
further.
 
C

Cowboy \(Gregory A. Beamer\)

1. Never use catch unless you are doing something with the error
2. If you find an exceptional condition, for example you can only accept
1-10 and someone sends in an 11, throw a custom exception
3. If you are not catching exceptions, do not add a catch simply to throw a
custom exception, UNLESS your exception will better explain the problem
(this can go back to checking input variables, ala rule #2).

In most cases, it is better to have your own exceptions except in cases
where you have NOTHING to add to the mix. If there are any business rules,
even if they cause SQL exceptions, create your own exception.

In the world of OO, this is part of encapsulation.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************************************************
Think outside the box!
*************************************************
 
S

Scott M.

2. If you find an exceptional condition, for example you can only accept
1-10 and someone sends in an 11, throw a custom exception

And ALWAYS validate end user input prior to accepting the data and working
with it to avoid the potential problems in the first place.
 
C

Cowboy \(Gregory A. Beamer\)

You = preacher
Me = choir

I forget who stated it (will probably remember as soon as I hit send):
"Never trust user input"!

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************************************************
Think outside the box!
*************************************************
 
J

Jon Skeet [C# MVP]

Scott M. said:
No Jon, my advice taken literally is exactly what I said "you should avoid
them when you can". Your interpretation of that was "don't use them because
tyhey can always be avoided".

Well, do you not agree that they *can* always be avoided? After all,
there are millions of lines of C out there which don't use exceptions,
using status codes instead.

I can't think of many cases where you *have* to throw an exception -
you *can* almost always avoid throwing them, but that doesn't mean you
*should* avoid throwing them in all those situations.
But, obviously (as you point out) avoiding an exception could cause other
problems down the line. In my opinion, that would fall into the "I guess I
need this exception and shouldn't avoid it" camp.

Right - and in that case you *can* avoid it, but shouldn't. To my mind,
that goes against your advice.
My advice was based on the OP, return a value vs. throw an exception. The
point was don't just throw an exception because you can.

Don't you see that there's a *huge* difference between "avoid
exceptions if you can" and "don't throw exceptions pointlessly"?

The trouble is, I can imagine lots of developers considering whether to
use an error code or an exception. I can't see how they could read your
advice without coming to the conclusion that you'd favour using an
error code - which is almost always a worse way of indicating errors
than using exceptions.


Obviously exceptions shouldn't be thrown just for the hell of it - but
I don't think they should be actively avoided, either.
 
C

Cor Ligthert [MVP]

Jon,

In my idea is the well written text from Scott, completely clear.

In VB it is easy to tell.
Never use an exception in a Sub because than giving back a Boolean or an
enum is more describing and as Scott wrote less consuming processing time.

Decide in a function if you can give a class with an error code in it.
Although in this case is in my idea throwing an exception more describing.

Translating this to C# gives than the answer on the exact OP question, you
should never let a Void method throw an exception but use a method that
gives back a boolean (or enum).

Just my thought,

Cor
 
J

Jon Skeet [C# MVP]

Cor said:
In my idea is the well written text from Scott, completely clear.

This is interesting, given that his clarification suggests that your
interpretation was not what was actually meant...
In VB it is easy to tell.
Never use an exception in a Sub because than giving back a Boolean or an
enum is more describing and as Scott wrote less consuming processing time.

No, a boolean or enum is *not* more descriptive than an exception. An
exception can give as much information as you want it to - a boolean or
an enum is a single value. Furthermore, turning the sub into a function
with a status code then demands that every call to it should check the
status code (assuming they care about error handling).

Do you really want to have to check a status code every time you add an
entry to a list?

Performance is a separate issue - have you read my page on it? Do you
have any experience of real life situations where exceptions were only
thrown in ways which most people would deem "reasonable" but where
performance was an issue?
Decide in a function if you can give a class with an error code in it.
Although in this case is in my idea throwing an exception more describing.

Translating this to C# gives than the answer on the exact OP question, you
should never let a Void method throw an exception but use a method that
gives back a boolean (or enum).

Well, I'm very glad you weren't part of designing the framework
classes. You'll find very few status codes there, and plenty of
exceptions being thrown by void methods.

Jon
 
P

Phil

Jon,

In my idea is the well written text from Scott, completely clear.

In VB it is easy to tell.
Never use an exception in a Sub because than giving back a Boolean or an
enum is more describing and as Scott wrote less consuming processing time.

Decide in a function if you can give a class with an error code in it.
Although in this case is in my idea throwing an exception more describing.

Translating this to C# gives than the answer on the exact OP question, you
should never let a Void method throw an exception but use a method that
gives back a boolean (or enum).

Just my thought,

Cor

But if you follow this advice you are back to old-style programming
where you have to check the return code of every function (which of
course, nobody ever does); you increase the size of your program and
slow it down with all the extra error checking code. Conversely if you
don't throw an exception then you never pay this penalty.

As Jon said, if exceptions are being raised so often that it is
becoming a performance problem then it's not a truly exceptional
situation and some redesign is in order (cf Int32.TryParse).
 
C

Cor Ligthert [MVP]

Phil,

I was specially folowing the thread from Scott.

He has not written that an error should be thrown for ever.

I was writting in the situation that you needed to return a possible error
and than you have in the case of a VB Sub. (I think it is confusing telling
this as a not Void method in C# because that does not tell direct the right
situation.) to return an class object including the error or to throw an
exception. (It is as well possible to pass an empty boolean variable by
value but that *I* find a bad way of programming).

See this link I showed to Jon as well, and see that it has only to be need
if there has to be checked for an error, what is written about this by Scott
as well.

http://msdn.microsoft.com/library/d...ystemwindowsformsopenfiledialogclasstopic.asp

Cor
 
J

Jon Skeet [C# MVP]

Cor said:
http://msdn.microsoft.com/library/d...ystemwindowsformsopenfiledialogclasstopic.asp

Before you start telling this is not returning an *error*.
An error is not something special, it is just something on what an action
would be taken.

I'm not sure which part of OpenFileDialog you're referring to, to be
honest. However, there are certainly situations where there can be
different statuses which don't mean that the call failed, just that
there are legitimate different non-error statuses.

Do you want me to give a list of subs which *do* throw exceptions
rather than returning status codes? I note you didn't answer about
having to check a status after calling ArrayList.Add each time...

Jon
 

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