Answered How to Know What Kind of Exception to Catch

aychekay

Member
Joined
Oct 10, 2011
Messages
11
Programming Experience
3-5
I realize this is probably a very elementary question. I'm using VB.Net 2008 to write an Outlook Addin and I'm very confused about what to put in my Catch block. How am I supposed to know what kind of exception object to try to catch in my catch block? Are exceptions relative to something? Will I catch one type of exception one time and a different type the next time?

I've already read through Daniel Turini's wonderful article on Exception Handling Best Practices over at CodeProject but that still didn't answer my question.

Sorry, my background is mostly Access VBA so VB.Net looks like some complicated monster although I'm sure I'll grow to like it over time.
 
Last edited:
First of all, you shouldn't be using a Try...Catch block at all if there isn't a reasonable chance that something can go wrong. While your application should have a single global exception handler, i.e. the UnhandledException event of the application, to gracefully handle all unanticipated errors, you shouldn't be adding Try...Catch blocks just in case. You need to understand what could go wrong with your code and why, and that will tell you whether to catch exceptions at all and, if so, which one(s).

Generally you only need to catch exceptions when there are things beyond your control. Examples of that include file I/O and data access. Your app might be designed to work with a specific database but there's no guarantee that the database is available when your app runs. As such, you have to allow for a possible exception when you Open your connection. Even if the connection opens successfully, there might be a network drop-out between that and executing a command against the database, so you still need to allow for that. An example of where you don't need to catch an exception is when the user enters a number into a TextBox. You can quite easily validate that data has been entered and that it's numeric before using it, so there's no need to catch an exception that might be caused by using invalid data.

In a large proportion of cases, if not the majority, you can check the documentation for the methods you're calling and they will tell you what exceptions they can throw and under what circumstances. You can determine which circumstances could reasonably arise and add the appropriate Catch blocks. The documentation won't tell you what exceptions can be thrown by the methods that those methods call though. Only experience, anticipation and some thorough testing can reveal those.
 
OK, that does clear it up quite a bit.

I'm already handling errors in MS Access just as you have stated so I'm familiar with the concept. One big difference is that there is only one object in VBA, an Err object which is very limiting in comparison to .NET's exceptions.
 
Back
Top