简体   繁体   中英

Try-Catch or Check Length?

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!

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 .

Checking the length is a much cheaper operation than catching an exception. When you have a try..catch block, it's adding extra structures into your code for catching exceptions - which is fine, I don't say it's wrong, but if you can check the length of the bounds then do that instead.

Throwing an exception is an expensive operation (as you have to generate a stack trace). Go with the length check.

I'd say "measure", if you're wondering which is more efficient for your situation.

For example: What if the out-of-bounds condition is extremely rare? So the out-of-bound never throws... In that case, all that extra "manual" bounds checking could be slower.

CAVEATS: The try/catch would need to be around many out of bounds-checks, so the setup of the try is less significant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM