When to create your own exception class?

A

Allan Ebdrup

Hi
I'm having a discussion with another programmer about a best practice for
thrownig exceptions. I want to create a rich class library with many
different exception classes in their own namespace, so they are easy to find
with intellisense. He wants to just throw Exception or one of the build in
exceptions. Do you have some good arguments for creating your own exception
classes even though they are little more than a type strongname and the same
as System.Exception (from witch they inherit)? We need the type strongname
to write specific catch blocks right?

Your input is appreciated.

I've read about exceptions here:

http://www.codeproject.com/dotnet/exceptionbestpractices.asp

http://www.ftponline.com/vsm/2003_05/online/wagner/

http://www.codeguru.com/Csharp/Csharp/cs_syntax/errorhandling/article.php/c8605/

http://www.dotnetspider.com/technology/kbpages/931.aspx

http://www.dotnetspider.com/technology/kb/ShowSample.aspx?SampleId=933

http://www.ondotnet.com/pub/a/dotnet/2001/09/04/error_handling.html

http://www.c-sharpcorner.com/Articles/ExceptionHandlingInCSKS004.asp

http://vsdntips.com/download/dotNet Coding Standards-sample.pdf

http://smccd.net/accounts/tilmann/cis_391_392/Slides/S_Handout S7.pdf

http://builder.com.com/5100-6387-1045391.html

http://www.javaspecialists.co.za/archive/Issue089.html

http://www.c2.com/cgi/wiki?ConvertExceptions

http://www.c2.com/cgi/wiki?JavaIdioms

http://www.javaworld.com/javatips/jw-javatip91_p.html

http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

http://www.onjava.com/pub/a/onjava/2004/09/29/smtp-logging.html?page=1

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfusingstatement.asp



Kind Regards,
Allan Ebdrup
 
J

Joanna Carter \(TeamB\)

I'm having a discussion with another programmer about a best practice for
thrownig exceptions. I want to create a rich class library with many
different exception classes in their own namespace, so they are easy to find
with intellisense. He wants to just throw Exception or one of the build in
exceptions. Do you have some good arguments for creating your own exception
classes even though they are little more than a type strongname and the same
as System.Exception (from witch they inherit)? We need the type strongname
to write specific catch blocks right?

Custom Exceptions are not just a "strong name", they can also carry extra
data and objects to enable you to take appropriate action on the exception.

e.g.

I have a Value Type framework that allows me to add custom validation before
and after a property of an object is set or changed. If the validation
fails, I raise an ValueTypeValidation exception that includes a reference to
both the original and changed values of the property. I can then use those
objects to display a message to the user stating the reason and values
involved, instead of one of those useless "An eror has ocurred" type
messages.

Joanna
 
C

Carlos J. Quintero [.NET MVP]

The actual point about exceptions is that they should:

- Provide a friendly message to the user in non-technical terms about what
happened, why and most important, how to recover from it
- A very detailed technical report to the developer, hidden behind a Details
button or included when sending a report.

So, if you don´t find a suitable exception in the framework to convey
specific information or to provide a detailed message with data (such as the
value that caused an "invalid argument" exception type), create a new
exception class and add it some properties. If you are rethrowing an
exception, you may want to encapsulate it (using the InnerException field)
to provide a better message or data, but don´t forget to include the inner
exception in the report that you receive as developer.

--
Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 
A

Allan Ebdrup

Ignacio Machin ( .NET/ C# MVP ) said:
Hi,


This has been discussed here, IIRC MS started promoting your idea, a
complex tree of exceptions each taking care of a particular event. Later
they changed their mind about the first approach.

Read this thread

http://groups-beta.google.com/group...%3Dmicrosoft.public.dotnet.*#203310d31b40351d

and this blog

http://blogs.msdn.com/brada/archive/2004/03/25/96251.aspx


My personal opinion is to keep it as simple as possible.

As I read the blog the problem is not defining new Exception classes, the
problem is making unessesary deep exception class trees. That's not what I'm
promoting, I'm promoting creating a flat hieracy of exception classes with a
good degree of detail that allows you to catch exceptions and handle the
exception correctly. Also I want a seperate namespace for all exceptions so
they are easier to find and easier to reuse.
If you use a Exception class in three different places and different
namespaces it doesen't belong in one of the classes namespaces.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,
As I read the blog the problem is not defining new Exception classes, the
problem is making unessesary deep exception class trees. That's not what
I'm promoting, I'm promoting creating a flat hieracy of exception classes
with a good degree of detail that allows you to catch exceptions and
handle the exception correctly. Also I want a seperate namespace for all
exceptions so they are easier to find and easier to reuse.
If you use a Exception class in three different places and different
namespaces it doesen't belong in one of the classes namespaces.

The problem with that approach is that you can get too detailed, and this
provoke the code to get complex and finally to ignore all the pretty
hierarchy of classes. Let me explain it further.

If you define one class for each possible condition each deriving from
Exception , let;s say 10 classes. then each code that call a method that can
throw any of them will need 10 catch clauses !!! :

try{
Thrower()
}
catch( MyException1 ex ) {}
catch( MyException2 ex ) {}
catch( MyException3 ex ) {}
catch( MyException4 ex ) {}
catch( MyException5 ex ) {}
catch( MyException6 ex ) {}
....

As you can see the code becomes complex, so after a while you will end with
a catch( Exception ex ) {} and forget about the "detailed" message, At the
end maybe the programmer and/or user only wants to know if there was an
error and not the details of it.


You need to think well before use such an approach, do you really need to
create all those exceptions types?
The answer is yes if you foresee a different action ( what is inside the
catch ) for each one,
if the default is getting a MessageBox saying there was an error, that
approach is nto the best


cheers,
 
J

Jon Skeet [C# MVP]

Carlos J. Quintero said:
The actual point about exceptions is that they should:

- Provide a friendly message to the user in non-technical terms about what
happened, why and most important, how to recover from it

I'm not at all convinced about that one. Chances are, the exception is
dealing with some concept that the user has *no* clue about. For
instance, say a parameter is null when it shouldn't be - how can you
explain that in non-technical terms? How many users are going to have
the faintest idea what null is?

In my experience, you need something at a much higher level to tell the
user that something has gone wrong. The message displayed may depend on
the exception generated, but it's unlikely to be known by the exception
itself.
 
C

Carlos J. Quintero [.NET MVP]

IMO, there are 2 kind of exceptions:

- The ones that are to "blame" the user: an incorrect format for some data,
a directory entered in a textbox that really does not exist, and attempt to
delete a record which has children, and so on. Of course, programs should
expose a good user interface to prevent those exceptions. For example, the
UI may validate that some data is required before causing a "primary key
missing" exception, but if they happen, the user can correct it if he is
provided with a friendly explanation.

- The ones that are not to "blame" the user, but the software or the system,
which are the majority. In this case, it is pointless to show the user the
description of the exception or the details, since he/she won´t understand
anything. A message like "This application has encountered an error which is
not your fault, please click the Send Report button and restart it" it is
more suitable, IMO.

Alan Cooper wrote a very good book (About Face) about user interfaces and
some chapter about how to deal with errors in apps...


--
Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


I prefer to use a mix approach, I present an user friendly message the most
exact I can (sometimes there is nothing more to tell him but a "An error has
occured, please reintent" or something similar )
and a "Details" button that dump the StackTrace , Message of the catched
exception as well as the inner exception.
In this way when the user call or email me he can give a clue of what
happened. I also create a .log file where I dump the error too.

I agree with you that in general the user has no clue of what caused the
error

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
C

Carlos J. Quintero [.NET MVP]

Yes, I use that approach too. I just wanted to point that instead of
spending a lot of time discussing is new exception types should be created
or not, we don´t have to miss the user's perspective and the user experience
when an exception happens.

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 
Top