By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,949 Members | 1,468 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,949 IT Pros & Developers. It's quick & easy.

How do you guys handle error's from class libraries?

P: n/a
Hi all,

I'm currently writing a load of class libraries, but not the main
application iteslf.

I want to provide some method for reporting errors back to the main
application.

At the moment I have a bool errBl and a string errMsg in my classes.
When errBl is ture, one could see what the error was in errMsg.

It works ok, but its quite clunky.

How do you guys do it? Trigger an event or something like that?

Thank you,
Andre

Nov 17 '05 #1
Share this Question
Share on Google+
17 Replies


P: n/a
Throw an exception whenever an error occurs that your component (class
library in this case) can't handle. This error will "bubble" up to your
client application where you can show the error to the user and let him/her
decide to retry the action or cancel. You can also trap this error higher up
in your architecture layer if you want to. The .NET framework has many
exception classes derived from the general Exception class. You can create
your own by subclassing Exception or one of its derivates. Look up "try",
"catch", "throw" and "finally" in the MSDN and you will find lots of
information. I can't see why you should create your own mechanism using
events, delegates, etc. Any reasons for that?
Nov 17 '05 #2

P: n/a
Hi,

One option is throwing exceptions, each time you detect some escenario
where you cannot recover, throw an exception, it should be handled by the
calling app.
In addition you could define a Log class, where you can log events that may
not be error but could help trace the working of the program. If the calling
app initialize the logging feature you use it, otherwise you do nothing.
cheers,

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

<ah****@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Hi all,

I'm currently writing a load of class libraries, but not the main
application iteslf.

I want to provide some method for reporting errors back to the main
application.

At the moment I have a bool errBl and a string errMsg in my classes.
When errBl is ture, one could see what the error was in errMsg.

It works ok, but its quite clunky.

How do you guys do it? Trigger an event or something like that?

Thank you,
Andre

Nov 17 '05 #3

P: n/a
Hi,

Thanks for the reply.

Yeah I use try and catch for handling the errors at the moment. The
issue is that I find it quite clumsy getting that error back to the
client.

I'm more interested in the "bubble up" process.

How do I get the error to the client when my assembly is quite far down
a hierarchy.

Say the main applications make use of an instance of class A, which
make use of an instance of class B, which make use of an instance of
class C.... Say an error occurred in class D, how would I get that
error back to C to B to A to the main application?

It seems quite clumsy doing it that way. Is there a way to pass a
message directly back to the main application from D, instead of going
through C, B, and A.

Maybe a central place for sending errors, which will trigger an event
on the client side?

Thanks,
Andre

Frode wrote:
Throw an exception whenever an error occurs that your component (class
library in this case) can't handle. This error will "bubble" up to your
client application where you can show the error to the user and let him/her
decide to retry the action or cancel. You can also trap this error higher up
in your architecture layer if you want to. The .NET framework has many
exception classes derived from the general Exception class. You can create
your own by subclassing Exception or one of its derivates. Look up "try",
"catch", "throw" and "finally" in the MSDN and you will find lots of
information. I can't see why you should create your own mechanism using
events, delegates, etc. Any reasons for that?


Nov 17 '05 #4

P: n/a
Generally speaking, exceptions that your library cannot handle on its
own should be allowed to bubble up to the point at which they can be
handled.

If an exception occurs inside your library, you should either re-throw
the same exception or throw a new user defined exception but include
the original exception in the InnerException property. You should
never swallow an exception or "mask" it.

It should be up to the developer who uses your library how to deal with
exceptions.

Nov 17 '05 #5

P: n/a
Also if the client violates an explicitly stated precondition of a
framework method, I would throw an exception in the call.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #6

P: n/a
<ah****@gmail.com> wrote:
Thanks for the reply.

Yeah I use try and catch for handling the errors at the moment. The
issue is that I find it quite clumsy getting that error back to the
client.

I'm more interested in the "bubble up" process.
That's exactly where exceptions come in.
How do I get the error to the client when my assembly is quite far down
a hierarchy.
You just let the exception get thrown back to an early stack frame.
Say the main applications make use of an instance of class A, which
make use of an instance of class B, which make use of an instance of
class C.... Say an error occurred in class D, how would I get that
error back to C to B to A to the main application?


Make D throw an exception, and make the main application catch it,
without making C, B or A catch it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7

P: n/a
It's not so hard as you might think.

Lets say you have one client-exe (A) and two class libraries (B,C)

button_click in A calls a method in B which uses a method in C. In C you
check the input parameters and find one parameter to be invalid. You decide
to report this back to the caller(s) as an error

C
---
if ( IsInvalidValue( parameter) )
throw new ArgumentException("Hey, you can't send that value
to me!")

this will generate an error, execution is halted and the call-stack reverses
back up to the client. If you have no try-catch around any of the calling
methods in the layer above (B), the error will continue up to the client
program and the click method (A). If you don't have a try-catch here, your
program will probably shut down (crash). If you have a try-catch in
button_click, you can display the error message in a messagebox in the catch
block.

A
----
try {
B.CallSomeMethod( myParameter );
} catch ( Exception ex ) { // catches all kinds of exceptions
MessageBox.Show( ex.Message )
}

you trap the bubble-up sequence in layer B by putting a try-catch around the
calling method

B
-----
retry:
try {
D.CallParanoidMethod( invalidParameter );
catch ( ArgumentException aex ) {
if ( CanFix( invalidParameter ) {
invalidParameter = Fix( invalidParameter );
goto retry
}
else
// Can't fix..re-throw exception (continue bubble up to client)
throw aex;
}
}

When an exception is thrown by the runtime (division by zero, etc) or you
throw one yourself, the thread returns immediatly to the caller(s). In some
cases you want clean-up code to dispose objects etc when an exception is
thrown. Then you have to put a "finally" block after the last "catch"-block.
All code inside the finally block will be executed no-matter-what before the
call is returned to the caller.

try {
throw new Exception("Doh!");
} finally {
CleanUpCode(); // Will always be executed immediatly after
// the error is thrown.
}

I would strongly recommend MSDN. Im sure you will understand the mechanism
really soon.
Nov 17 '05 #8

P: n/a
Excellent. That's just what I'm after. Thanks for that.

A couple of other issues:

1) Performance: If I were to be lazy and just catch exceptions of type
System.Exception in each class. Ex:

Class B
----------------
void SomeMethod()
{
try
{
c.SomeMethod();
}
catch(Exception ex)
{
throw ex;
}
}

Class C
----------------
void SomeMethod()
{
try
{
d.SomeMethod();
}
catch(Exception ex)
{
throw ex;
}
}

Would that have a dramatic impact on my application's performance if I
don't use more specific exception's (like IOException, or
SqlException)?

2) Design related: It just seems quite tedious and repetative to add a
try catch block in every method. Is there no way to have it a bit
cleaner? I suppose its not to bad though.

Thanks,
Andre

Frode wrote:
It's not so hard as you might think.

Lets say you have one client-exe (A) and two class libraries (B,C)

button_click in A calls a method in B which uses a method in C. In C you
check the input parameters and find one parameter to be invalid. You decide
to report this back to the caller(s) as an error

C
---
if ( IsInvalidValue( parameter) )
throw new ArgumentException("Hey, you can't send that value
to me!")

this will generate an error, execution is halted and the call-stack reverses
back up to the client. If you have no try-catch around any of the calling
methods in the layer above (B), the error will continue up to the client
program and the click method (A). If you don't have a try-catch here, your
program will probably shut down (crash). If you have a try-catch in
button_click, you can display the error message in a messagebox in the catch
block.

A
----
try {
B.CallSomeMethod( myParameter );
} catch ( Exception ex ) { // catches all kinds of exceptions
MessageBox.Show( ex.Message )
}

you trap the bubble-up sequence in layer B by putting a try-catch around the
calling method

B
-----
retry:
try {
D.CallParanoidMethod( invalidParameter );
catch ( ArgumentException aex ) {
if ( CanFix( invalidParameter ) {
invalidParameter = Fix( invalidParameter );
goto retry
}
else
// Can't fix..re-throw exception (continue bubble up to client)
throw aex;
}
}

When an exception is thrown by the runtime (division by zero, etc) or you
throw one yourself, the thread returns immediatly to the caller(s). In some
cases you want clean-up code to dispose objects etc when an exception is
thrown. Then you have to put a "finally" block after the last "catch"-block.
All code inside the finally block will be executed no-matter-what before the
call is returned to the caller.

try {
throw new Exception("Doh!");
} finally {
CleanUpCode(); // Will always be executed immediatly after
// the error is thrown.
}

I would strongly recommend MSDN. Im sure you will understand the mechanism
really soon.


Nov 17 '05 #9

P: n/a
Andre,

You only have to try/catch in methods where you actually can "fix" the
exception and the code-behaviour (try other methods, etc). Otherwise, just
drop try/catch, and let the client handle the error (most common, I think).

There should be no performance impact other than that you have to type-cast
to the exception specific class you want to handle.

.... catch ( Exception ex ) {
if ( ex is ArgumentException ) {
AgrumentException argEx = (ArgumentException)ex;
.......
} else if ( ex is ApplicationException ) {
ApplicationException appEx = (ApplicationException)ex;
.........
}
}

obviously

....catch ( ArgumentException argEx ) {
............
} catch ( ApplicationException appEx ) {
.........
} catch ( Exception ex ) {
......
}

is a much better object-oritented (and cleaner) approach. But remember to
place the most specific (specialized) exceptions in the first catch
blocks...if you place Exception first, Application and Argument -exception
won't be caught(!!)
If you just want to check that an (any) exception has occured and you don't
need the error message (or any other exception-specific properties), you can
just

try {
C.CallBuggedCode();
} catch {
Console.WriteLine("An error occured") // <- I hate this error message
;)
}

-------------
Frode
"ah****@gmail.com" wrote:
Excellent. That's just what I'm after. Thanks for that.

A couple of other issues:

1) Performance: If I were to be lazy and just catch exceptions of type
System.Exception in each class. Ex:

Class B
----------------
void SomeMethod()
{
try
{
c.SomeMethod();
}
catch(Exception ex)
{
throw ex;
}
}

Class C
----------------
void SomeMethod()
{
try
{
d.SomeMethod();
}
catch(Exception ex)
{
throw ex;
}
}

Would that have a dramatic impact on my application's performance if I
don't use more specific exception's (like IOException, or
SqlException)?

2) Design related: It just seems quite tedious and repetative to add a
try catch block in every method. Is there no way to have it a bit
cleaner? I suppose its not to bad though.

Thanks,
Andre

Frode wrote:
It's not so hard as you might think.

Lets say you have one client-exe (A) and two class libraries (B,C)

button_click in A calls a method in B which uses a method in C. In C you
check the input parameters and find one parameter to be invalid. You decide
to report this back to the caller(s) as an error

C
---
if ( IsInvalidValue( parameter) )
throw new ArgumentException("Hey, you can't send that value
to me!")

this will generate an error, execution is halted and the call-stack reverses
back up to the client. If you have no try-catch around any of the calling
methods in the layer above (B), the error will continue up to the client
program and the click method (A). If you don't have a try-catch here, your
program will probably shut down (crash). If you have a try-catch in
button_click, you can display the error message in a messagebox in the catch
block.

A
----
try {
B.CallSomeMethod( myParameter );
} catch ( Exception ex ) { // catches all kinds of exceptions
MessageBox.Show( ex.Message )
}

you trap the bubble-up sequence in layer B by putting a try-catch around the
calling method

B
-----
retry:
try {
D.CallParanoidMethod( invalidParameter );
catch ( ArgumentException aex ) {
if ( CanFix( invalidParameter ) {
invalidParameter = Fix( invalidParameter );
goto retry
}
else
// Can't fix..re-throw exception (continue bubble up to client)
throw aex;
}
}

When an exception is thrown by the runtime (division by zero, etc) or you
throw one yourself, the thread returns immediatly to the caller(s). In some
cases you want clean-up code to dispose objects etc when an exception is
thrown. Then you have to put a "finally" block after the last "catch"-block.
All code inside the finally block will be executed no-matter-what before the
call is returned to the caller.

try {
throw new Exception("Doh!");
} finally {
CleanUpCode(); // Will always be executed immediatly after
// the error is thrown.
}

I would strongly recommend MSDN. Im sure you will understand the mechanism
really soon.


Nov 17 '05 #10

P: n/a
> is a much better object-oritented (and cleaner) approach. But remember to
place the most specific (specialized) exceptions in the first catch
blocks...if you place Exception first, Application and Argument -exception
won't be caught(!!)


hmm..bad english...Application and Argument exceptions will of course be
caught, but not as their specific exceptions...they will be caught as
Exception only. The reason for this is because ApplicationArgument,
ArgumentException and all other specialized exceptions inherits from the
Exception class and therefore will be trapped by the Exception catch-block
which is executed first...
Nov 17 '05 #11

P: n/a
Frode <Fr***@discussions.microsoft.com> wrote:
is a much better object-oritented (and cleaner) approach. But remember to
place the most specific (specialized) exceptions in the first catch
blocks...if you place Exception first, Application and Argument -exception
won't be caught(!!)


hmm..bad english...Application and Argument exceptions will of course be
caught, but not as their specific exceptions...they will be caught as
Exception only. The reason for this is because ApplicationArgument,
ArgumentException and all other specialized exceptions inherits from the
Exception class and therefore will be trapped by the Exception catch-block
which is executed first...


Actually, that's not true - it will fail to compile, with an error such
as:

Test.cs(16,16): error CS0160: A previous catch clause already catches
all exceptions of this or a super type ('System.Exception')

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #12

P: n/a
Jon,

You are absolutly right. I was jumping to fast to the conclusion without
checking - my mistake.
--
-------------
Frode
"Jon Skeet [C# MVP]" wrote:
Frode <Fr***@discussions.microsoft.com> wrote:
is a much better object-oritented (and cleaner) approach. But remember to
place the most specific (specialized) exceptions in the first catch
blocks...if you place Exception first, Application and Argument -exception
won't be caught(!!)


hmm..bad english...Application and Argument exceptions will of course be
caught, but not as their specific exceptions...they will be caught as
Exception only. The reason for this is because ApplicationArgument,
ArgumentException and all other specialized exceptions inherits from the
Exception class and therefore will be trapped by the Exception catch-block
which is executed first...


Actually, that's not true - it will fail to compile, with an error such
as:

Test.cs(16,16): error CS0160: A previous catch clause already catches
all exceptions of this or a super type ('System.Exception')

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

Nov 17 '05 #13

P: n/a
Hi Ignacio,

Yeah I'm doing that at the moment.

Thanks for the post,
Andre

Nov 17 '05 #14

P: n/a
Hi Chris,

Thanks for the little InnerException tip.

Many thanks,
Andre

Nov 17 '05 #15

P: n/a
Also,

Would it not be a good design to provide a way for the client to
"plug-in" some functionality into my library (and in this case for
error handling)?

So when a client instantiates my class, I'll provide the option for the
client to specify an error handling method?

Ex: First I show how the client will use the Library, then I show some
public delegate, and finally the implementation of the Library class

//Client
//Error function
public void DisplayError(string message)
{....}

//use of Library
ShowError myShowError = new ShowError(DisplayError);

Library myLibrary = new Library(myShowError);
//Some public delegate
public delegate void ShowError(string message);

//Library
//Member
ShowError _showError;

//Constructor
public Library()
{..}

public Library(ShowError showError)
{ _showError = showError; }

public TriggerError()
{
if(_showError != null)
_showError("Display this error to client");
else
throw new Exception...
}

Is this a viable solution?

Is it bad practice to have the error handling in the library rather
than at the client. I'm just thinking that it'll be a real hasstle to
do a try{} catch on the client for frequently used Libraries.

I'd appreciate any comments regarding the design.

Nov 17 '05 #16

P: n/a
<ah****@gmail.com> wrote:
Would it not be a good design to provide a way for the client to
"plug-in" some functionality into my library (and in this case for
error handling)?
The furthest I'd go with that is to allow the client to specify a
logger - and that could be used for diagnostics as well as errors. I
wouldn't try to *handle* the error though.
Is it bad practice to have the error handling in the library rather
than at the client.
Yes, unless the library can truly handle the error and still fulfil its
contract.
I'm just thinking that it'll be a real hasstle to
do a try{} catch on the client for frequently used Libraries.


The client shouldn't be putting try/catch all over the place, because
exceptions shouldn't be generated in the normal success case - usually
you put a try/catch against specific exceptions that you know you can
handle and continue from, and at the top level of the application to
report truly unexpected and unrecoverable (per unit of work) errors to
the user.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #17

P: n/a
Thant makes sense. Thanks Jon.

Jon wrote:
<ah****@gmail.com> wrote:
Would it not be a good design to provide a way for the client to
"plug-in" some functionality into my library (and in this case for
error handling)?


The furthest I'd go with that is to allow the client to specify a
logger - and that could be used for diagnostics as well as errors. I
wouldn't try to *handle* the error though.
Is it bad practice to have the error handling in the library rather
than at the client.


Yes, unless the library can truly handle the error and still fulfil its
contract.
I'm just thinking that it'll be a real hasstle to
do a try{} catch on the client for frequently used Libraries.


The client shouldn't be putting try/catch all over the place, because
exceptions shouldn't be generated in the normal success case - usually
you put a try/catch against specific exceptions that you know you can
handle and continue from, and at the top level of the application to
report truly unexpected and unrecoverable (per unit of work) errors to
the user.

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


Nov 17 '05 #18

This discussion thread is closed

Replies have been disabled for this discussion.