When implementing your own methods, you should throw an exception when the method
cannot complete its task as indicated by its name. When you want to throw an exception,
there are two issues that you really need to think about and consider:
• What Exception-derived type are you going to throw? You really want to select a type
that is meaningful here. Consider the code that is higher up the call stack and how that
code might want to determine that a method failed in order to execute some graceful
recovery code. You can use a type that is already defined in the FCL, but there may not
be one in the FCL that matches your exact semantics. So you'll probably need to define
your own type, derived directly from System.Exception. If you want to define an exception
type hierarchy, it is highly recommended that the hierarchy be shallow and wide in
order to create as few base classes as possible. The reason is that base classes act as a way
of treating lots of errors as one error, and this is usually dangerous. Along these lines,
you should never throw a System.Exception type, and you should use extreme caution
if you do throw any other base class exception type.
• What string message are you going to pass to the exception type's constructor? When
you throw an exception, you should include a string message with detailed information
indicating why the method couldn't complete its task. If the exception is caught and
handled, this string message is not seen. However, if the exception becomes an unhandled
exception, this message is usually logged. An unhandled exception indicates a true
bug in the application, and a developer must get involved to fix the bug. An end user will
not have the source code or the ability to fix the code and re-compile it. In fact, this
string message should not be shown to an end user. So these string messages can be
very technically detailed and as geeky as is necessary to help developers fix their code.
Furthermore, since all developers have to speak English (at least to some degree, since
programming languages and the FCL classes and methods are in English), there is usually
no need to localize exception string messages. However, you may want to localize
the strings if you are building a class library that will be used by developers who speak
different languages. Microsoft localizes the exception messages thrown by the FCL,
since developers all over the world will be using this class library.