In this our final article on C#.Net custom exception handling, we dive more deeply into the use of Reflection when calling custom exceptions.

As stated before, custom exception handling is often seen a low-level luxury. If you have it, then you enjoy it. If you don’t, then it is not really missed. But tailored systems of all kinds benefit from a solid infrastructure. Whether you are building a CRM application, Accounting application, Line-of-Business application, or some combination of these systems … custom exception handling will go a long way toward making your implementation more robust and easier to maintain.

In the previous article, we described using Reflection in the assembly that throws the custom exception like this:

if( user.IsLostAndConfused ) { throw new EagleException( customMessage, MethodInfo.GetCurrentMethod().ReflectedType.FullName); }

Now what does this accomplish? It might look a little obscure, so let’s walk through an example.

Let’s say that you have a solution consisting of five projects:

  • EagleDataAccessLibrary
  • EagleBusinessLogicLibrary
  • EagleWebService
  • EagleSilverlightApp
  • EagleWindowsApp

And let’s say that each of these contains dozens of classes and hundreds of methods. Without using Reflection, you will not know exactly which assembly and exactly which method threw the exception. You might be left wondering exactly where the exception occurred in your code.

However, if the calling assembly uses reflection as described above (and if you create a constructor that accepts these strings), then you might get a parameter that looks like this:

Eagle.Libraries.DataAccess, Version=1.7152.495.30320, Culture=neutral, PublicKeyToken=null

You can then log this along with the message, and you will know exactly which assembly threw the exception.

If the calling assembly goes one step further to also send the name of the exact method as well (by sending MethodInfo.GetCurrentMethod().Name), then you might get a parameter like this:

Eagle.Libraries.DataAccess.GetCustomer

This way, you will have a big head-start when you review the log at a later date and want to hunt-down the cause of some exception!

This concludes our article series on using custom exceptions in a .Net application. This is certainly not the only way to handle custom exceptions in .Net, and it might not even be the best way. But if you are not using custom exceptions now, then hopefully this article series will help you do so in a meaningful way. As a result, your Intelligent ERP (iERP) system will be even smarter than it was before!


blog comments powered by Disqus
Written by Administrator   
Monday, 06 June 2011 21:26