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 Exception
object for many reasons. If you throw an instance of the Exception
base class, then calling code has no choice but to catch Exception
if 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.
It's the overhead of throwing an exception itself (creating the object, walking the stack, etc.) that's costly. Making your own exception class adds almost no overhead, so if you're going to throw an exception, don't make it new Exception("message")
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With