473,785 Members | 2,863 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 #1
43 2117
From the horse mouth:
http://blogs.msdn.com/kcwalina/archi...16/396787.aspx

"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 #2
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.
Aug 13 '06 #3
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.
"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 #4
I think that article sums it up quite nicely:

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


"Shehab Kamal" <Sh*********@di scussions.micro soft.comwrote in message
news:CA******** *************** ***********@mic rosoft.com...
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.

Aug 13 '06 #5
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
CustomerNotFoun d 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
"Shehab Kamal" <Sh*********@di scussions.micro soft.comwrote in message
news:CA******** *************** ***********@mic rosoft.com...
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.

Aug 13 '06 #6
Shehab Kamal <Sh*********@di scussions.micro soft.comwrote:
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

--
http://barrkel.blogspot.com/
Aug 13 '06 #7
"Scott M." <s-***@nospam.nosp amwrote:
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>.TryGet Value. These are best
suited to 'leaf' operations, operations that don't go off and call some
deep graph of other methods.

-- Barry

--
http://barrkel.blogspot.com/
Aug 13 '06 #8
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 13 '06 #9
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.

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
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 13 '06 #10

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

Similar topics

19
3225
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
1433
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
12061
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
4563
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
9480
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10152
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...
1
10092
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
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
8974
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
5381
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
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
3
2880
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.