473,761 Members | 5,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception handling best practices

Is this good style? I always have to catch the generic System.Exceptio n
because our system supports nested transactions that is BeginTransactio n
increases the level, Commit decreases it, rollback sets it to zero, and only
if the level reaches zero the commit/rollback statement is sended to the
database.

try
{
BeginTransactio n();
// stuff
Commit();
}
catch (SpecialExcepti on e)
{
Rollback();
throw new ApplicationExce ption(e.Message );
}
catch (Exception)
{
Rollback();
throw;
}
Jul 21 '05 #1
2 3489
Couple of points about:
catch (SpecialExcepti on e) ...
The statement:
throw new ApplicationExce ption(e.Message );

is usually not a good practice. You should instead use something like this:
throw new ApplicationExce ption("Some context message that provides
additional meaning to the user.",e);

The original statement would work but usually is not a good practice - all
you are doing is changing the exception type, but you are losing the
original stack trace and are not providing any additional information at
all.

One justification for the original statement is if there is security
sensitive information in the original exception that you do not want exposed
to a higher level component and you wish to hide the data.

An additional reason for transforming the exception type is if the exception
that is caught (SpecialExcepti on), is a custom exception that is defined in
an assembly that is not available to modules that have called into your code
(e.g. they are calling across a boundary, either appdomain, machine, etc).
In this case you actually do need to discard the original type and replace
it with a different type. This is because if the calling module does not
have access to the assembly then it will not be able to deserialize the
exception object and that will itself cause another exception to be thrown,
masking the original exception.

In either case I would preserve the original exception message and add
additional context information to aid users in figuring out why it didn't
work.

Another point is that use of the type ApplicationExce ption is being
discouraged as it does not really add much value. There is a ongoing debate
about this and it has not yet been resolved in any camp's favor, but I
personally never use it anymore - I either use a custom exception (rare), or
use the same exception type that was caught (i.e. clone the type), or
sometimes just use Exception.
Couple of points about
catch (Exception)
{
Rollback();
throw;
}

Again, this works, but due to a bug in the current version of the runtime it
will lose the original stack information and replace it with a stack that
begins where the throw statement occurs. This is supposed to be fixed in
Whidbey. It also does not add any context information.

I usually prefer to catch-wrap-throw rather then simply rethrow the original
exception. In this case I would probably use something like...

catch (SpecialExcepti on e)
{
Rollback();
throw new Exception("Unab le to complete.",e);
}
catch(Exception ex)
{
Rollback();
throw new Exception("I fell down and can't get up.",ex);
}

I always prefer to add information in order to make life as easy as possible
for the users - cryptic error messages should be avoided at all costs.
"cody" <de********@gmx .de> wrote in message
news:un******** ******@TK2MSFTN GP10.phx.gbl...
Is this good style? I always have to catch the generic System.Exceptio n
because our system supports nested transactions that is BeginTransactio n
increases the level, Commit decreases it, rollback sets it to zero, and
only
if the level reaches zero the commit/rollback statement is sended to the
database.

try
{
BeginTransactio n();
// stuff
Commit();
}
catch (SpecialExcepti on e)
{
Rollback();
throw new ApplicationExce ption(e.Message );
}
catch (Exception)
{
Rollback();
throw;
}

Jul 21 '05 #2
> One justification for the original statement is if there is security
sensitive information in the original exception that you do not want
exposed to a higher level component and you wish to hide the data.

An additional reason for transforming the exception type is if the
exception that is caught (SpecialExcepti on), is a custom exception that is
defined in an assembly that is not available to modules that have called
into your code
Good points, I never thought about that.
Another point is that use of the type ApplicationExce ption is being
discouraged as it does not really add much value.
You are right but we started our project with using ApplicationExce ption as
convention so we have to finish it like that because now most of our modules
expect now our components to throw only ApplicationExce ption and its
descendants :(
catch(Exception ex)
{
Rollback();
throw new Exception("I fell down and can't get up.",ex);
}

I always prefer to add information in order to make life as easy as
possible for the users - cryptic error messages should be avoided at all
costs.


The catch(Exception ) was thought only for the theoretically impossible case
but I think in that case it is better that the messagebox displays the user
the original exception message ("cannot connect to database") than my own
text ("something really fouled up during creation of customer").
Jul 21 '05 #3

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

Similar topics

6
2341
by: Daniel Wilson | last post by:
I am having exception-handling and stability problems with .NET. I will have a block of managed code inside try...catch and will still get a generic ..NET exception box that will tell me which assemblies are loaded before shutting down. In one case, some of my DB-accessing code didn't handle a NULL value properly. But try...catch wouldn't catch the exception and keep going. I'd just get the error message and then it would shut the...
6
1140
by: ORC | last post by:
I'm looking for a good article that explains how exception handling should be implemented in an application. It's not only the tecnical implementation (try-catch-final thing) but a good general rule to follow I wanted. Are you aware of one you would recommend? Thanks, Ole
44
4226
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level user tasks should always be included in a try/catch block that actually handles any exceptions that occur (log the exception, display a message box, etc.). 2. Low-level operations that are used to carry out the high level tasks
1
2059
by: aftab Alam | last post by:
Hi All, I have am working on C# 2.0 for a project and need to know the best practices for exception handling. At the moment I am doing it as Follows. I have a Manager class that is supposed to update entries in the Dictionary and Database as well, to separate DataBase Layer I have written another library that contains static methods and does some updating in data base..
1
258
by: Jon | last post by:
Can someone point me to a best practices for exception handling in .Net 2? We have a method that we like for ASP.Net apps on .Net 1.1, but are just moving to 2.0 with winforms apps. Is it still recommended to use the addHandler method in each form for ApplicationThreadExceptions and then just handle everything else using try/catch blocks and rethrow if the exception can't be handled? Is it recommended to let all exceptions bubble up...
1
4142
by: David Herbst | last post by:
Enterprise Library Jan 2006 with Visual Studio 2005 on Windows 2000 Server sp4. My custom exception formatter fails with a "Unable to handle exception: 'LoggingExceptionHandler'." exception. When I attached the debugger to the process and stepped into the code it executed without error. In both cases I was running a Debug build, the only difference in the case that works is that I attached the debugger to the same exact binaries....
10
1507
by: tony | last post by:
Hello!! As you know every user defined exception must be derived from class Exception. Now to my question if I write catch then every exception will be caught. If I instead write catch(Exception) then every exception will also be caught. These two will catch the exact same exception is this right understod?
1
2511
by: maciek | last post by:
Hi, I was wondering if anyone could suggest me a book/article/tutorial on Exception Handling in multi tier Windows Apps. What are the best practices/ways to implement EH in multi tier enviroment. I read some MS Best Practices articles on MSDN. It helped a little, but considering how unexperienced programmer I am, I think I'd need a good sample code and explanation I could follow to fully understand the issue. Thanks in advance.
24
2197
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?
0
2536
by: =?Utf-8?B?UG9sbHkgQW5uYQ==?= | last post by:
Hi, I have previously used EL v 3.1 Exception Handling application block successfully. I thought I would now try to do the same with EL v 4.0. My first experiment was to replace an exception. I created a project and added the following references - 1/ Enterprise Library Exception Handling Application Block v 4.0
0
9377
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
10136
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
9989
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
9925
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
8814
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
7358
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
5266
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3509
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.