Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C# (http://www.programmingforums.org/forum16.html)
-   -   Exception Handling and Events (http://www.programmingforums.org/showthread.php?t=14902)

InfoGeek Jan 8th, 2008 10:09 PM

Exception Handling and Events
 
Hi Friends!
I have been away for a while, now I'm planning to come back here and participate actively again.
Anyways, coming to the question:-
As per my understanding, we should not place try... catch statements in every function where we want to handle exceptions instead we should let the exceptions rise up in the function call hierarchy and handle all the exceptions at one place. That sounds fine. But I'm having problems using this technique in event driven programming. For example, I have a C# windows application and I open one main form from where I can open several pop-up forms. Now, I want to handle all the exceptions in the main form. Now suppose, In one pop-up form, I've a button and I attach one Click event handler to that. and In that event handler, an Exception is thrown, I cannot catch that exception in the main form as the event wasn't raised from the main form but the button class. Any suggestions how can I implement this?

InfoGeek Jan 9th, 2008 12:31 AM

Re: Exception Handling and Events
 
I found something related to the above here . I'll look into it in detail later on.

xavier Jan 9th, 2008 12:45 AM

Re: Exception Handling and Events
 
Attaching to Application.ThreadException - will only help you when an unexpected exception happens (and you'll show something like - app died , sorry :) ) - but there are cases when certain exception can be caught and recovered from.

So, i think that exceptions shouldn't be caught only at top level, but that every form can catch some exceptions also.

lectricpharaoh Jan 9th, 2008 2:10 AM

Re: Exception Handling and Events
 
Quote:

Originally Posted by InfoGeek
As per my understanding, we should not place try... catch statements in every function where we want to handle exceptions instead we should let the exceptions rise up in the function call hierarchy and handle all the exceptions at one place.

Actually, it's often good practice to catch exceptions as close to where they are raised as possible. This results in more reliable code, as well as potentially more efficient code (the stack doesn't have to unwind as far, which results in fewer 'dead' references, and thus less work for the GC).

Of course, doing it this way means sprinkling the code with try/catch blocks, which can clutter up the code. Your best option is probably to design the code in such a way as to limit which exceptions can be thrown when, and then wrap this localized code in a try/catch block.


All times are GMT -5. The time now is 3:40 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC