is it better to prevent exception with a guard clause or catch the exception? There is a best practice? Pro and cons of the two methodologies?
For example is better this:
try
{
param=myArray[3];
}
catch (IndexOutOfRangeException e)
{
do something...
}
or this:
if(myArray.Length < 4)
{
do something...
}
else
{
param=myArray[3];
}
Thank you all for the answers :)
is it better to prevent exception with a guard clause or catch the exception?
In the case of "boneheaded" exceptions like index out of range, always the former.
In the case of "exogenous" exceptions, always the latter.
Pro and cons of the two methodologies?
There are only cons of the latter in the case of boneheaded exceptions. They are:
Finally, you should read my article on this subject.
http://ericlippert.com/2008/09/10/vexing-exceptions/
Use a guard clause - catching the exception incurs a high runtime cost, and in general to improve readability you should only use exceptions for error conditions, not for normal control flow
Guard clause. You never want to use try
/catch
for control flow. Catching exceptions is expensive and should be avoided as much as you can.
In cases where the Exception can be prevented, prevent it. Always.
Catching and handling Exceptions is expensive and should never be used for normal control flow. A guard is cheap and easy.
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