Exceptions in .NET–part V

When someone with lots of experience in Win32 programming starts using .NET, they tend to be shocked with the regular use of exceptions. In fact, they tend to ask why do we define APIs which don’t return error codes and rely heavily on exceptions. Well, it’s a matter of “culture”. Notice that .NET and OO allows a developer to be very productive. For instance, just look at all those fluent APIs we have. For instance, here’s a snippet from Fluent NH:

HasMany( pat => pat.Documentos)
.Access.CamelCaseField( Prefix.Underscore )
.AsBag( )
.Cascade.All( )
.Inverse(  )
.KeyColumn( “IdPats” )
.Not.LazyLoad( );

When I write code like this, I’m assuming that all of those methods calls will be executed without errors. Code would need to be much more tedious if we had to check for errors in all those calls. I mean, we have lots of things going on here and we didn’t even went into the IL… It’s really hard to write defensive code for all of this and, in this case, I’m ok with getting an exception in the mappings that ends up terminating my app. Even though this might be a chock for people coming from Win32, the truth is that the productivity gains from doing this kind of things makes it “all right” to rely heavily in exceptions when you’re writing ,NET code.

So, we simply rely in catching known exceptions and understanding that things will go well most of the times. Notice, however, that we do get several interesting assurances from the CLR to mitigate state corruption:

  • a thread can’t be aborted when executing code is inside a catch or finally block;
  • we can rely on CERs (constrained execution regions) to reduce potential exceptions (more about this in a future post);

Even though these assurances do help, there will be times when you end up with corrupted data. In these cases, you probably should terminate your app’s process immediately. I’d say that the bottom line is that managed code has a different philosophy  and it probably is a good option if you’re writing  applications which can be terminated when data corruption occurs.

And that’s it for now. On the next post I’ll present some of the guidelines I try to follow when working with exceptions. Stay tuned for more.

Advertisements

~ by Luis Abreu on September 9, 2011.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: