Not everyone realises that you can have multiple Catch clauses per Try clause. The point in this is that you can catch different types of Exception.
You may have a function which can throw several different types of Exception. You can catch specific types of Exception separately and deal with each of them differently.
For example, you may wish to do something like this (nb. these Exception classes are made up – they aren’t in the .NET framework)…
Try
DBConn.ExecQuery(Query)
Catch ex as ForeignKeyException 'inherits from KeyException
MsgBox("Sorry - this query would cause a conflict with another table")
Catch ex as KeyException
MsgBox("Sorry - this data is not valid")
Catch ex as ConnectionException
MsgBox("The database connection has gone down. Please reconnect and try again")
Catch ex as Exception
MsgBox("Something else went wrong - " & ex.Message)
End Try
Note that catch clauses will catch any object of inherited Exception classes as well as the class that you specify, so if you need to catch a more specific type of Exception, you need to put it before a less specific type, which is why ForeignKeyException comes before KeyException, and everything comes before Exception.
- 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, Coding, Solutions, Structured Exception Handling











