Consider throwing exceptions instead of returning HRESULTs or some other type of error code. With well-placed exception handling code, you should not have to rely on methods that return error codes such as an HRESULT or a Boolean true/false to correctly handle errors, which makes for much cleaner code. Another benefit is that you do not have to look up any HRESULT values or any other type of error code to understand the code. However, the biggest advantage is that when an exceptional situation arises, you cannot just ignore it as you can with error codes.
This technique is especially useful when writing a managed C# component that is called by one or more COM objects. Throwing an exception is much cleaner and easier to read than returning an HRESULT. The managed wrapper that the runtime creates for your managed object will make a clean and consistent conversion between the exception type and its corresponding HRESULT value.
Throw specific exceptions, not general ones. For example, throw an ArgumentNullException instead of ArgumentException, which is the base class of ArgumentNullException. Throwing an ArgumentException just tells you that there was a problem with a parameter value to a method. Throwing an ArgumentNullException tells you more specifically what the problem with the parameter really is. Another potential problem is that a more general thrown exception may not be caught if you are looking for a more specific type derived from the thrown exception.
There are several types of exceptions built-in to the FCL that you will find very useful to throw in your own code. Many of these exceptions are listed here with a definition of where and when they should be thrown:
Many exceptions that derive from the SystemException class, such as NullReferenceException, ExecutionEngineException, StackOverflowException, OutOfMemoryException, and IndexOutOfRangeException are thrown only by the CLR and should not be explicitly thrown with the throw keyword in your code.
Popularity: 2% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply