A friend has asked me to write some articles on how to handle exceptions in .NET, so here we go… A little bit of background first: –
Exceptions occur when things go wrong or other exceptional circumstances. They are a bit more complicated than the older error trapping systems, but the complexity lets you do a lot with them. Every Exception is an object, and it is either an object of type Exception, or of a type that inherits from Exception.
In this post, I’m just going to deal with catching a general Exception. I’ll cover what you can do with the Exception class itself, multiple Catch clauses, different Exception types, re-throwing and creating your own Exception classes in other posts.
So here is the way it works. When something goes wrong, an Exception object gets created and “thrown”. This means that the stack rewinds back until it finds something that catches the Exception. Basically, this means that anything that gets called inside a Try clause will be handled if an Exception gets thrown. Not only that, but any functions that that calls etc. on and on either forever or until there is another Try clause that will handle it. “Later” Try clauses take precedence over earlier ones.
This is how to use it…
Catch ex as Exception
Some exception handling code
Cleanup code that gets called whatever
Note that the Finally clause is actually optional – it is fine to leave it out. You would normally use it if you wanted to close a database connection, file, stream, network connection etc. or some other form of cleanup code. Also, you can have multiple Catch clauses, but I’ll cover that later.