c# - Is it better using a guard clause or catching the exception? -


is better prevent exception guard clause or catch exception? there best practice? pro , cons of 2 methodologies?

for example better this:

try {      param=myarray[3]; } catch (indexoutofrangeexception e) {     something... } 

or this:

if(myarray.length < 4) {     something... } else {     param=myarray[3]; } 

thank answers :)

is better prevent exception guard clause or catch exception?

in case of "boneheaded" exceptions index out of range, former.

in case of "exogenous" exceptions, latter.

pro , cons of 2 methodologies?

there cons of latter in case of boneheaded exceptions. are:

  • exceptions incredibly expensive compared tests.
  • exceptions intended model exceptionally rare control flow situations; if potentially accessing index out of range normal don't write exception handler.
  • exceptions reported "first chance" exceptions listeners even if exception handled. many systems -- asp, example -- listen first chance exceptions, log of them, , treat components produce lot of them buggy, because they are. (i once introduced deliberate first-chance exception in common code path in asp , day later boy did hear it. buggy-subsystem tests went crazy.)
  • there exceptions call "boneheaded" exceptions -- null dereference, index out of range, , on -- because easy avoid , indicate failures dangerous should always treated fatal bugs , never handled (unless "handler" logging them before shutting down process.) don't handle bug, eliminate bug.

finally, should read article on subject.

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


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -