473,769 Members | 6,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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
17 7612
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
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.c om> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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
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
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
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
<ah****@gmail.c om> 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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7
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 ArgumentExcepti on("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.CallSomeMetho d( 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.CallParanoidM ethod( invalidParamete r );
catch ( ArgumentExcepti on aex ) {
if ( CanFix( invalidParamete r ) {
invalidParamete r = Fix( invalidParamete r );
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
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.Exceptio n 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 ArgumentExcepti on("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.CallSomeMetho d( 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.CallParanoidM ethod( invalidParamete r );
catch ( ArgumentExcepti on aex ) {
if ( CanFix( invalidParamete r ) {
invalidParamete r = Fix( invalidParamete r );
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
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 ArgumentExcepti on ) {
AgrumentExcepti on argEx = (ArgumentExcept ion)ex;
.......
} else if ( ex is ApplicationExce ption ) {
ApplicationExce ption appEx = (ApplicationExc eption)ex;
.........
}
}

obviously

....catch ( ArgumentExcepti on argEx ) {
............
} catch ( ApplicationExce ption 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.CallBuggedCod e();
} catch {
Console.WriteLi ne("An error occured") // <- I hate this error message
;)
}

-------------
Frode
"ah****@gmail.c om" 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.Exceptio n 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 ArgumentExcepti on("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.CallSomeMetho d( 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.CallParanoidM ethod( invalidParamete r );
catch ( ArgumentExcepti on aex ) {
if ( CanFix( invalidParamete r ) {
invalidParamete r = Fix( invalidParamete r );
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

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

Similar topics

1
3179
by: Craig Ringer | last post by:
Hi folks I'm a bit of a newbie here, though I've tried to appropriately research this issue before posting. I've found a lot of questions, a few answers that don't really answer quite what I'm looking for, but nothing that really solves or explains all this. I'll admit to being stumped, hence my question here. I'm also trying to make this post as clear and detailed as possible. Unfortunately, that means it's come out like a book. I...
7
3256
by: Tony Johansson | last post by:
Hello!! Assume I have a handle body pattern with classes called Handle and Body. In the Body class I store one int value for example 7 or some other integer value. In the Handle class I have a pointer to the Body class. If a want to create a STL container of List with the following declaration List <Handle <Body> > list
14
2733
by: Howard | last post by:
Hi, I recently had a problem where I decided to store objects in a vector. (Previously, I had always stored pointers in vectors). Well, naturally, when storing an object in a vector, using push_back, the object I had in hand was getting copied (twice, in fact). That led to a problem, in that my object contained a "handle" to another object, and when the object being pushed went out of scope and was destroyed, the referenced object was...
4
2474
by: atv | last post by:
Whatis the proper way to handle errors from function calls? For example, i normally have a main function, with calls to mine or c functions. Should i check for errors in the functions called themselves, or should i return a code to main and handle the error there? If i don't return them to main, except for the structure, what use is the main function except for calling functions?
6
2873
by: Leandro Berti via DotNetMonster.com | last post by:
Hi All, I wrote a code to do serial communication with an equipament. When i use the code outside of threaded class it seens work properly, but when i put inside a class and execute a thread in the first seconds the communication is ok, later i receive read/write error. I?ve been in MSDN site and there i discover that the read/write error is a INVALID_HANDLE problem. But why??? I just create the serial communication file and use it....
2
596
by: Jonathan Boivin | last post by:
Hi people, Let me introduce to how I get this error. I have a form which load all my bills representation depending upon filters which each bill is a usercontrol of my own having some textboxes containing bill's datas. (I already replaced the labels by painting the text instead.) When I click on my filter button, it clears the current usercontrol bills and load the new ones upon the current chosen filters. The bug happens when
2
35621
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently. Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting...
3
3153
by: Peterwkc | last post by:
Hello all C++ expert programmer, I have a handle class which point to another class and use the pointer as object. I follow the code from C++ articles submited by someone in this forum. Unfortunately, my compilation is failed. Below is my code : // Main.cpp
6
38064
by: muby | last post by:
Hi everybody :) I'm modifying a C++ code in VC++ 2005 my code snippet void BandwidthAllocationScheduler::insert( Message* msg, BOOL* QueueIsFull,
0
9423
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
10049
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
9997
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
9865
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...
1
7413
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
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5309
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.