473,847 Members | 1,698 Online
Bytes | Software Development & Data Engineering Community
+ 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 1574
* "SStory" <Th*******@TAKE OUTTHISSPAMBUST ERsofthome.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*******@TAKE OUTTHISSPAMBUST ERsofthome.net> wrote in message
news:eN******** ********@TK2MSF TNGP11.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 ArgumentExcepti on or
ArgumentNullExc eption or ArgumentOutOfRa ngeException on invalid input. This
will prevent you throwing confusing exceptions later, like an unhelpful
NullReferenceEx ception or IndexOutOfRange Exception.

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
InvalidOperatio nException if the object is in the incorrect state (eg not
"open", or "conneced" or "initialize d").

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 InvalidCastExce ption or a NullReferenceEx ception,
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*******@TAKE OUTTHISSPAMBUST ERsofthome.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" <davidbaxterbro wne no potted me**@hotmail.co m> wrote in
message news:uu******** *****@tk2msftng p13.phx.gbl...

"SStory" <Th*******@TAKE OUTTHISSPAMBUST ERsofthome.net> wrote in message
news:eN******** ********@TK2MSF TNGP11.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 ArgumentExcepti on or
ArgumentNullExc eption or ArgumentOutOfRa ngeException on invalid input.

This will prevent you throwing confusing exceptions later, like an unhelpful
NullReferenceEx ception or IndexOutOfRange Exception.

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
InvalidOperatio nException if the object is in the incorrect state (eg not
"open", or "conneced" or "initialize d").

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 InvalidCastExce ption or a NullReferenceEx ception,
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.Http Application.Err or event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomai n.UnhandledExce ption event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows. Forms.Applicati on.ThreadExcept ion 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.Thr eadException 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.Thr eadException 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*******@TAKE OUTTHISSPAMBUST ERsofthome.net> wrote in message
news:eN******** ********@TK2MSF TNGP11.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******** ******@TK2MSFTN GP10.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.Http Application.Err or event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomai n.UnhandledExce ption event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows. Forms.Applicati on.ThreadExcept ion 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.Thr eadException 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.Thr eadException 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*******@TAKE OUTTHISSPAMBUST ERsofthome.net> wrote in message
news:eN******** ********@TK2MSF TNGP11.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*******@TAKE OUTTHISSPAMBUST ERsofthome.net> wrote in message
news:eN******** ********@TK2MSF TNGP11.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******** *******@TK2MSFT NGP12.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*******@TAKE OUTTHISSPAMBUST ERsofthome.net> wrote in message
news:eN******** ********@TK2MSF TNGP11.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
1646
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
9492
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 code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
8
7824
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 some method I would Cath the error and Re-Throw it! The question is: what are the issues of this approach? Would I have performance problems cus of my catches? What does MS recommends in such a situation??
10
3490
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 somewhere that each folder under the "web site" is compiled in separate assembly. I however, did not find that the "web site" creation in vs.net 2005 created any AssemblyInfo.cs file.
6
1640
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 of connecting late and disconnecting early. Background: - multi-tier application (code-behind uses properties and methods of the business object, the business object handles the data layer) For instance (in an ASPX code-behind file):
24
2205
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 the UI layer to a method in a library class that calls the stored procedure. Best to return a boolean indicating success/failure, return a string with the exception message, or just return the entire exception?
13
1528
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 functions, especially for those that consider the error exceptions management. I have the next alternatives but I think there are better: Alternative 1: ============= def ExecuteSQL(cmdSQL, cursor):
2
1982
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 information I have come across seems to revolve around using validation controls on the webpages themselves, which is not always feasible. Regards,
6
1186
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 attributes as "public readonly" in order to protect the attributes from getting modified yet still accessible by the parent class. I am not convinced that this is the best practice for this. Implementing properties seem like a bit of a waste of time to...
0
9730
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
10983
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
10647
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
9482
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...
1
7882
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5911
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4528
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
2
4119
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3164
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.