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…
Try Some code Catch ex as Exception Some exception handling code Finally Cleanup code that gets called whatever End Try
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.
- Structured Exception Handling in .NET Part 1: Try/Catch/Finally
- Structured Exception Handling in .NET Part 2: Multiple Catch Clauses and Different Exception Types
- Structured Exception Handling in .NET Part 3: The Exception Class
- Structured Exception Handling in .NET Part 4: Re-Throwing Exceptions
- Structured Exception Handling in .NET Part 5: Throwing new Exceptions
No related posts.
Tags: .NET, .NET 2.0, .NET 3.5, Coding, Object Orientation, Structured Exception Handling












[...] I mentioned earlier, throwing Exceptions can be a very useful way of notifying the appropriate code that something [...]