473,796 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception vs Boolean

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, NullReferenceEx ception, IndexOutOfRange Exception and so on, or my
own exceptions be thrown?

Thanks in advance,
Shehab.
Aug 13 '06
43 2120
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!
*************** *************** *************** ****
"Shehab Kamal" <Sh*********@di scussions.micro soft.comwrote in message
news:2F******** *************** ***********@mic rosoft.com...
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, NullReferenceEx ception, IndexOutOfRange Exception and so on, or
my
own exceptions be thrown?

Thanks in advance,
Shehab.

Aug 13 '06 #11
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.
Aug 14 '06 #12
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!
*************** *************** *************** ****
"Scott M." <s-***@nospam.nosp amwrote in message
news:eL******** ******@TK2MSFTN GP03.phx.gbl...
>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.

Aug 14 '06 #13
Scott M. <s-***@nospam.nosp amwrote:
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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 14 '06 #14
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

"Jon Skeet [C# MVP]" <sk***@pobox.co mschreef in bericht
news:MP******** *************** *@msnews.micros oft.com...
Scott M. <s-***@nospam.nosp amwrote:
>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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Aug 14 '06 #15
Cor Ligthert [MVP] wrote:
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

Aug 14 '06 #16
On Mon, 14 Aug 2006 09:34:31 +0200, "Cor Ligthert [MVP]"
<no************ @planet.nlwrote :
>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) .
--
Phil
Aug 14 '06 #17
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.
http://msdn.microsoft.com/library/de...classtopic.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.

Cor
Aug 14 '06 #18
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/de...classtopic.asp

Cor

"Phil" <fo*@foo.comsch reef in bericht
news:fl******** *************** *********@4ax.c om...
On Mon, 14 Aug 2006 09:34:31 +0200, "Cor Ligthert [MVP]"
<no************ @planet.nlwrote :
>>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) .
--
Phil

Aug 14 '06 #19
Cor Ligthert [MVP] wrote:
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.
http://msdn.microsoft.com/library/de...classtopic.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

Aug 14 '06 #20

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

Similar topics

19
3229
by: Diego F. | last post by:
I think I'll never come across that error. It happens when running code from a DLL that tries to write to disk. I added permissions in the project folder, the wwwroot and in IIS to NETWORK_SERVICE and Everyone, with Full Control to see if it's a permissions problem. The project is hosted in a Windows 2003 Server and developed from PCs in a domain, developing with Visual Studio 2005 Beta 1. -- Regards,
6
4056
by: Steve Long | last post by:
Help, I'm running VS.NET 2003 and when I try to start my application, I get the "unhandled exception" dialog instead of the IDE highlighting the offending line of code. The problem appears to be instantiating a particular class in my project but the dialog doesn't tell me what code in the class is causing the problem (and it a large class). How can I get the IDE to take me to the offending line of code? If I put this line in my...
1
4142
by: David Herbst | last post by:
Enterprise Library Jan 2006 with Visual Studio 2005 on Windows 2000 Server sp4. My custom exception formatter fails with a "Unable to handle exception: 'LoggingExceptionHandler'." exception. When I attached the debugger to the process and stepped into the code it executed without error. In both cases I was running a Debug build, the only difference in the case that works is that I attached the debugger to the same exact binaries....
4
1766
by: Shimon Sim | last post by:
I just switch my asp application to .net 2 and got this error. Any reasons why? Thank you. Server Error in '/RAFEmployee' Application. -------------------------------------------------------------------------------- The specified module could not be found. (Exception from HRESULT: 0x8007007E) Description: An unhandled exception occurred during the execution of the
0
1434
by: alf | last post by:
I have an app that was running in my local server using full trust, now I moved it to hosting company wish run in Medium trust. Then I get a Security exception (details below) Then I configured my local server to run in Medium level, trying to catch the problem in the app. The problem is that the behavior is random !! sometime all pages run succesfully, but some time I get the exception in any page. I'm trying to find a way to debug the...
5
7562
by: cozsmin | last post by:
hello , as u know wait() and notify() will not thow an exception if the method that calls them has the lock , or esle i misundrestood java :P this is the code that throws (unwanted) exceptions : (or u can download it from : http://www.geocities.com/mndt_0/files/WaitingForThread.java at this link it has the spaces )
3
12062
by: Mike | last post by:
Hi I have problem as folow: Caught Exception: System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. (machine.config) ---> System.Security.SecurityException: Request for the permission of type
0
1389
by: star111792 | last post by:
helo all i am working with JSP and EJBs. i have written a simple code for verifying username and password of user by using session beans. my problem is that i am getting the following exception: type Exception report message
4
23543
by: yogarajan | last post by:
The specified module could not be found. (Exception from HRESULT: 0x8007007E) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileNotFoundException: The specified module could not be found. (Exception from HRESULT: 0x8007007E) Source Error: An unhandled...
3
4564
by: chandhrakv | last post by:
Event code: 3005 Event message: An unhandled exception has occurred. Event time: 11/18/2009 3:03:53 PM Event time (UTC): 11/18/2009 9:33:53 AM Event ID: ef3014ea80424b00b1bc2e7095fffe4c Event sequence: 34707 Event occurrence: 17 Event detail code: 0 Process information:
0
9673
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10452
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10221
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10003
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9050
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5440
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2924
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.