Re: Try/Catch
- Posted by Spock Feb 10, 2015
- 4767 views
It can. I explained this already in an earlier post.
If you're referring to:
1) Don't crash the program but return the element nearest the index value
2) Emit a console message warning of the out-of-bounds index
Perhaps I should have been more clear with my language.
By "error code", I mean a returned value from call that indicates there was a problem executing the routine. As an example, if an open() routine fails to open a file, it returns an error code instead of a valid handle.
By "recover", I mean that the code stops executing code at the level where the error took place, and returns control to a higher level in the execution stack, which can act on the error condition.
Returning "the element nearest the index value" is only the correct action to take in a very narrow set of conditions.
Likewise, assuming that the end user will be knowledgeable enough to understand a console warning message is very unlikely.
Your solution effectively ignores the error condition, and continues execution despite knowing the result of the operation is in error.
For that reason, it fails to match the criteria.
- David
David,
To recover from, eg, a bad index, either there is recovery code inside try/catch construct or at the caller point. Recovery code is needed somewhere and it makes more sense to have it at the caller point.
How does your try/catch idea correctly know how to recover from a bad index? In 99.99% of cases it won't - unless you place it at the caller point. So why not just have an explicit test there anyway?
Try/catch won't somehow magically give you program correctness.
If the program accesses the error/status code inside the called routine the compiler will insist that the caller check this outside after each call. Or at least issue a warning so that the programmer knows about it. That would solve the issue of knowing where to check for errors.
I think the problem of a bad index is a very poor example to solve using try/catch. So you catch a bad index. Now what?
Spock