Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Catch or Check Length?

Tags:

c#

try-catch

I was just wondering which would be cheaper, using a try catch block for index out of bounds or checking the length of a multi dimensional array and comparing values?

I have a feeling it's the length, since I can store the length in a variable and then just do if's which are relatively cheap. I'm just not sure how expensive try-catch is.

Thanks!

like image 915
Shaded Avatar asked Nov 27 '22 05:11

Shaded


1 Answers

Throwing an exception is extremely expensive compared to checking the value of an integer. However, that's irrelevant. What is more important is that even if exceptions were cheap, they would still be the wrong choice. The point of an exception is that it represents an exceptional occurrance. Exceptions ideally should only be used to represent something unexpected, rare, and preferably fatal.

Another way of looking at it: If you're accessing an array outside its bounds, you have a bug. Fix the bug. An exception handler hides the bug, it doesn't fix the bug.

like image 64
Eric Lippert Avatar answered Dec 30 '22 02:12

Eric Lippert