I’ve read that throwing exceptions is an expensive operation. However, doesn’t creating your own exceptions make your code more expressive and readable?
Some of my coworkers suggest that you should just use System.Exception and insert your custom text into the message instead of creating a new custom exception.
I’m interested in other opinions. Appreciate any suggestions.
Do not throw
System.Exception. Ever.The problem with it resides in the calling code. It is a bad practice to catch the general
Exceptionobject for many reasons. If you throw an instance of theExceptionbase class, then calling code has no choice but to catchExceptionif they want to handle it. This forces the calling code to use a bad practice.Also, the calling code has no reliable means of distinguishing what the exception was, if all it gets is
Exception.It is typically best to use one of the pre-defined exceptions if any are applicable (
ArgumentException,InvalidOperationException, etc.). If none correctly describe the situation, then a custom exception class is a perfectly good way to go.