473,467 Members | 1,549 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Best Practices Class Exceptions

When I right a class, I am wondering what are the best practices for error
handling?

Do I try..catch and trap the error and if so what do I do with it? Because
most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the same
thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.

thanks,

Shane
Nov 21 '05 #1
8 1548
* "SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> scripsit:
Do I try..catch and trap the error and if so what do I do with it? Because
most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the same
thing the original exception already has so I think what is the point?


Take a look at the constructor of 'Exception'. You can specify an
'InnerException' there. Catch the exception and create a new exception
object and specify the caught exception as inner exception.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>
Nov 21 '05 #2

"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl...
When I right a class, I am wondering what are the best practices for error
handling?

Do I try..catch and trap the error and if so what do I do with it? Because most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the same thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.


If you're really writing a class library, the rules are a little more
strict. For a library designer you should validate all of your input
arguments and immediately throw an ArgumentException or
ArgumentNullException or ArgumentOutOfRangeException on invalid input. This
will prevent you throwing confusing exceptions later, like an unhelpful
NullReferenceException or IndexOutOfRangeException.

If your type is stateful, and your methods can only be called when the
object is in a certian state then you should check that and throw an
InvalidOperationException if the object is in the incorrect state (eg not
"open", or "conneced" or "initialized").

In addition you should document if a particular kind of exception is
especially likely to be thrown.

But these are really all examples of a general proposition. The exceptions
thrown by a class library should clearly indicate what really went wrong.
You shold never throw an InvalidCastException or a NullReferenceException,
but you shouldn't really catch them either. Rather you should structure
your code and validate your inputs so that these exceptions don't get thrown
in the first place.

You should catch and rethrow exceptions when either the type of the
exception is misleading, or you need to bundle information from that stack
level to make the exception meaningful. I find custom exceptions only
really usefull for bundling common state information into a thrown
exception. So if you find yourself concatenating the same kinds of
information into a thrown exception's error message, condisder adding your
own Exception subtype with instance fields to hold this information.

David

Nov 21 '05 #3
Yes but the question is do I want to?
What do I gain by that?
Suppose I write a class

and then I use that class

when I call method X, wouldn't I just want to try catch around that call and
not have the method trap the error, since the one needing to handing it
would be the calling app?

I am confused about this, and not sure what the best practice is.

Thanks,

Shane
"Herfried K. Wagner [MVP]" <hi***************@gmx.at> wrote in message
news:2o************@uni-berlin.de...
* "SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> scripsit:
Do I try..catch and trap the error and if so what do I do with it? Because most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the same thing the original exception already has so I think what is the point?


Take a look at the constructor of 'Exception'. You can specify an
'InnerException' there. Catch the exception and create a new exception
object and specify the caught exception as inner exception.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 21 '05 #4
Thanks for the thoughts.
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> wrote in
message news:uu*************@tk2msftngp13.phx.gbl...

"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl...
When I right a class, I am wondering what are the best practices for error handling?

Do I try..catch and trap the error and if so what do I do with it? Because
most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the

same
thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.


If you're really writing a class library, the rules are a little more
strict. For a library designer you should validate all of your input
arguments and immediately throw an ArgumentException or
ArgumentNullException or ArgumentOutOfRangeException on invalid input.

This will prevent you throwing confusing exceptions later, like an unhelpful
NullReferenceException or IndexOutOfRangeException.

If your type is stateful, and your methods can only be called when the
object is in a certian state then you should check that and throw an
InvalidOperationException if the object is in the incorrect state (eg not
"open", or "conneced" or "initialized").

In addition you should document if a particular kind of exception is
especially likely to be thrown.

But these are really all examples of a general proposition. The exceptions thrown by a class library should clearly indicate what really went wrong.
You shold never throw an InvalidCastException or a NullReferenceException,
but you shouldn't really catch them either. Rather you should structure
your code and validate your inputs so that these exceptions don't get thrown in the first place.

You should catch and rethrow exceptions when either the type of the
exception is misleading, or you need to bundle information from that stack
level to make the exception meaningful. I find custom exceptions only
really usefull for bundling common state information into a thrown
exception. So if you find yourself concatenating the same kinds of
information into a thrown exception's error message, condisder adding your
own Exception subtype with instance fields to hold this information.

David

Nov 21 '05 #5
Shane,
Do I try..catch and trap the error and if so what do I do with it? IMHO that is the big question: "what do I do with it", if you do not have a
specific answer to that question, IMHO you should NOT be catching the
exception.

Ergo I find it better to not catch exceptions, rather I simply let them
float up to the Global Exception Handlers. That is not to say that I don't
use Try/Catch, I use Try/Catch where I have something specific to do with
that specific exception.

In other words Try/Finally is good, Try/Catch not so good.

See the MSDN Mag article below for details.

I normally use a global exception handler for logging and display to the
user. I use try/finally more then I use try/catch. I only use try/catch when
there is something specific that I need to do with the exception, otherwise
I let my global exception handlers handle the exception.

Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.HttpApplication.Error event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomain.UnhandledException event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows.Forms.Application.ThreadException event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as
well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when you
use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/is...T/default.aspx

For example: In my Windows Forms apps I would have a handler attached to the
Application.ThreadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the MainForm
raises an exception, the Application.ThreadException handler will catch all

uncaught exceptions from any form/control event handlers.

Note David has some excellent comments on argument validation to your class
libraries. Especially if those class libraries are going to be used outside
of your current solution.

Hope this helps
Jay
"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl... When I right a class, I am wondering what are the best practices for error
handling?

Do I try..catch and trap the error and if so what do I do with it? Because most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the same thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.

thanks,

Shane

Nov 21 '05 #6
Yes it does help.
Thanks Jay, for all the good information. I am of the same thought....if I
don't need to do anything with it, let it float up and be dealt with by the
caller. Unless it is a public class library.

Shane

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
news:e8**************@TK2MSFTNGP10.phx.gbl...
Shane,
Do I try..catch and trap the error and if so what do I do with it? IMHO that is the big question: "what do I do with it", if you do not have

a specific answer to that question, IMHO you should NOT be catching the
exception.

Ergo I find it better to not catch exceptions, rather I simply let them
float up to the Global Exception Handlers. That is not to say that I don't
use Try/Catch, I use Try/Catch where I have something specific to do with
that specific exception.

In other words Try/Finally is good, Try/Catch not so good.

See the MSDN Mag article below for details.

I normally use a global exception handler for logging and display to the
user. I use try/finally more then I use try/catch. I only use try/catch when there is something specific that I need to do with the exception, otherwise I let my global exception handlers handle the exception.

Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.HttpApplication.Error event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomain.UnhandledException event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows.Forms.Application.ThreadException event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as
well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when you use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/is...T/default.aspx

For example: In my Windows Forms apps I would have a handler attached to the Application.ThreadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the MainForm raises an exception, the Application.ThreadException handler will catch all
uncaught exceptions from any form/control event handlers.

Note David has some excellent comments on argument validation to your class libraries. Especially if those class libraries are going to be used outside of your current solution.

Hope this helps
Jay
"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl...
When I right a class, I am wondering what are the best practices for error handling?

Do I try..catch and trap the error and if so what do I do with it?

Because
most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the

same
thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.

thanks,

Shane


Nov 21 '05 #7
In addition to the other recommendations, when I'm writing classes that
could be invoked in a stateless environment, or where throwing an exception
could cause confusion with some types of other components (generally COM and
ASP classes, but frequently in ASPX pages), I use boolean methods and
maintain some properties to hold the last error details. This works quite
nicely by itself or in concert with local SEH. If a method returns false,
the caller knows something went wrong underneath it. If it still has a
reference to the object, it can interrogate the error detail property(ies)
and decide whether to act on it or send it back up the chain; at least it
knows whatever was being done failed.

Alan
"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl...
When I right a class, I am wondering what are the best practices for error
handling?

Do I try..catch and trap the error and if so what do I do with it?
Because
most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the
same
thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.

thanks,

Shane

Nov 21 '05 #8
Thanks J.,

I have used that method in the past also.

Shane
"J. Alan Rueckgauer" <vo**@dev.nul> wrote in message
news:uy***************@TK2MSFTNGP12.phx.gbl...
In addition to the other recommendations, when I'm writing classes that
could be invoked in a stateless environment, or where throwing an exception could cause confusion with some types of other components (generally COM and ASP classes, but frequently in ASPX pages), I use boolean methods and
maintain some properties to hold the last error details. This works quite
nicely by itself or in concert with local SEH. If a method returns false,
the caller knows something went wrong underneath it. If it still has a
reference to the object, it can interrogate the error detail property(ies)
and decide whether to act on it or send it back up the chain; at least it
knows whatever was being done failed.

Alan
"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl...
When I right a class, I am wondering what are the best practices for error handling?

Do I try..catch and trap the error and if so what do I do with it?
Because
most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?

I know I could catch it and throw my own, but I'd have to tell them the
same
thing the original exception already has so I think what is the point?

Please give me some best practices advice on this.

thanks,

Shane


Nov 21 '05 #9

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

Similar topics

3
by: Sasha | last post by:
Hi everybody, I would like to hear your thoughts on the following problem. We have the following classes. Class Exam int ID* int Version* string Name
136
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their...
8
by: Daniel Portal | last post by:
Hi there, I'm in 3-tier project and I'm thinking about having Try / Catch statements in each method, just in case you know! If the case is that I don't have a special treatment for the error in...
10
by: jojobar | last post by:
Hello, I am trying to use vs.net 2005 to migrate a project originally in vs.net 2003. I started with creation of a "web site", and then created folders for each component of the site. I read...
6
by: Nate | last post by:
I am in a slight predicament trying to determine the most efficient and effective way to connect/disconnect from a database within a business object (c# dll). I'm also keeping in mind the concept...
24
by: Earl | last post by:
I have all of my data operations in a separate library, so I'm looking for what might be termed "best practices" on a return type from those classes. For example, let's say I send an update from...
13
by: vizcayno | last post by:
Hello: Need your help in the "correct" definition of the next function. If necessary, I would like to know about a web site or documentation that tells me about best practices in defining...
2
by: hardieca | last post by:
Hi, I'd like to know if anyone knows of any resources detailing the best practices of validating rules in the business tier and providing helpful error messages to users in the UI tier. All the...
6
dennison
by: dennison | last post by:
I am trying to write code for a class that has a couple of attributes that will can only be known upon creation. Because I think accessor functions (e.g. getSomething()) are outdate, I declared my...
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
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,...
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
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...
1
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...
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
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,...
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...
0
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 ...

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.