Why is it preferable to throw this Exception
Throw New DivideByZeroException("You can't divide by zero")
over this general one:
Throw New Exception("You can't divide by zero")
What advantage is gained in this particular example? The message already tell it all. Do standard subclasses that inherit from the base Exception class ever have different methods that the base? I haven’t seen a case, but I must admit that I tend to throw the base Exception.
The type of the exception allows handlers of the exception to filter it. If all you threw were exceptions of type
Exceptionhow would handlers know what exceptions to catch and which to allow to propagate up the call stack?For example, if you always throw
Exception:How does the caller
Fooknow if a null exception occurred or if theInt32.Parse()failed? It has to check the type of the thrown exception (or do some nasty string comparison).It’s even more worrisome if you get a
ThreadAbortExceptionorOutOfMemoryExceptionwhich can occur in spots you wouldn’t expect an exception. In these cases if your catching code only catchesExceptionyou may mask these (important) exceptions and cause damage to your program (or system) state.The example code should read: