Saturday, October 14, 2006

Exception−Handling Tips

Structured exception handling is very important, but you should not overuse it. Here are some important tips to make sure you do not:


  • Avoid using Visual Basic exception handling for anything other than handling errors. Often,developers will find that TryCatchFinally blocks make for interesting flow−control structures, but using them for this purpose only serves to damage the structural integrity of the program and consume resources.


  • Creating custom exception classes for every error you might encounter doesn't make sense. Creating equivalents of the run−time exception classes only wastes time and resources.


  • Notwithstanding the usefulness of the Throw feature, you should handle exceptions, as far as possible, in the method in which they were raised. This, too, conserves resources and makes your code easier to follow.


  • When using nested Try blocks or multiple Catch blocks, you need to remember to place the default Catch E As Exception as the last Catch block, because placing it earlier will prevent any later exception classes (both custom or built−in) from ever getting executed.


  • Handle all exceptions; do not simply catch exceptions and then do nothing with them. Providing "sterile" exception−handling code does not mean you do not have to deal with the exceptions, and they should not merely be "swept under the carpet."