3 ms·
How do you propose handling an OOB index in an array?
by eeereerews 6y ago
How do you propose handling an OOB index in an array?
- twic 6y agoI follow Joe Duffy in recognising that we should make a distinction between "errors" and "bugs" [0]. IOException is an error; out of bounds access, division by zero, assertion failures, and things like ClassCastException and NullPointerException in Java, are bugs. For errors, you should do error handling, which means you want the compiler to make sure you don't miss them. For bugs, you want to let the program bomb out, either aborting entirely or stopping at some high-level boundary from which it's possible to sanely continue. In Java, unchecked exceptions are a mostly adequate mechanism for that. Rust's catch_unwind is better, because it makes stronger guarantees [1]. Erlang's approach of terminating the thread and throwing away its heap is also very good, if you can apply that. [0] http://joeduffyblog.com/2016/02/07/the-error-model/#bugs-arent-recoverable-errors http://joeduffyblog.com/2016/02/07/the-error-model/#bugs-are... [1] https://doc.rust-lang.org/std/panic/fn.catch_unwind.html https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
- eeereerews 6y agoBut once you've accepted unchecked exceptions (and paid the cost of the having them), it just doesn't make sense to only use them only for bugs. For example, it is better to try: x = json['foo']['bar'][i] catch OOB: handle error than to if not (json is a dict and 'foo' in json and json['foo'] is a dict and ...): handle error x = json['foo']['bar'][i] even though in the former, unchecked exceptions are used for non-bugs.
- nicoburns 6y agoThe idea is that for bugs you don't even need a try-catch (or maybe one around your entire program). And pattern matching and functions like `map` make the second case much nicer.