[(VB.NET focus)]
Some tips on using exceptions
Exceptions are cool, but it's all too easy to overuse them—at the cost of performance. Here are three tips on using exceptions, but they all come down to variations on the rule that exceptions are supposed to be exceptional. In other words, remember that exception handling isn't supposed to replace testing for the obvious. You don't, for example, use exceptions to test for EOF conditions. Similarly:
- Don't micromanage exceptions by wrapping every possible statement in a Try-Catch block. It's usually better to wrap the whole action in a single Try statement than to have multiple Try statements.
- Don't squelch exceptions by writing code like this without a very good reason:
Catch e as Exception
- This is the equivalent of blindly using On Error Resume Next in older VB code and is bad for the same reasons. If an exception happens, either handle it or propagate it.
Which leads to the final rule—what we like to call "the good fellowship rule" for exceptions:
- If you don't handle an exceptional condition completely and need to rethrow an exception to the calling code, add enough information (or create a new exception class) so that the code you're communicating with knows exactly what happened and what you did to (try to) fix it.
[Source: Visual Basic Developer June 2001]