As I mentioned earlier, throwing Exceptions can be a very useful way of notifying the appropriate code that something unexpected happened. In order to throw an Exception, first you create an object of type Exception, or a class which inherits from Exception if there is a more appropriate one. You should also set the Message property, which can usually be done from a constructor. You can actually do all this in a single line. eg.
Throw New Exception(“Invalid username”)
Some Exception classes will want additional data, depending on the type of Exception that you are notifying about. It is worth looking around the .NET framework or any other set of code that you are using to see what Exceptions are available. I will post up some common ones in a later post.
- 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