Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better using a guard clause or catching the exception? [closed]

Tags:

java

c#

exception

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 :)

like image 557
Fabio Marcolini Avatar asked May 10 '13 14:05

Fabio Marcolini


4 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:

  • Exceptions are incredibly expensive compared to tests.
  • Exceptions are intended to model exceptionally rare control flow situations; if potentially accessing an index out of range is normal then don't write an exception handler.
  • Exceptions are reported as "first chance" exceptions to listeners even if the exception is handled. Many systems -- ASP, for example -- listen for first chance exceptions, log all of them, and treat components that produce a lot of them as buggy, because they are. (I once introduced a deliberate first-chance exception in a common code path in ASP and a day later boy did I hear about it. The buggy-subsystem tests went crazy.)
  • There are some exceptions that I call the "boneheaded" exceptions -- null dereference, index out of range, and so on -- that because they are so easy to avoid and indicate failures so obviously dangerous that they should always be treated as fatal bugs and never handled (unless the "handler" is logging them before shutting down the process.) Don't handle the bug, eliminate the bug.

Finally, you should read my article on this subject.

http://ericlippert.com/2008/09/10/vexing-exceptions/

like image 179
Eric Lippert Avatar answered Nov 16 '22 20:11

Eric Lippert


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

like image 26
Zim-Zam O'Pootertoot Avatar answered Nov 16 '22 20:11

Zim-Zam O'Pootertoot


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.

like image 5
Dave Zych Avatar answered Nov 16 '22 18:11

Dave Zych


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.

like image 4
Justin Niessner Avatar answered Nov 16 '22 18:11

Justin Niessner