5 ms·
Yeah but you aren't really capturing the difference fully. If all of the exception handling code is at the end of the block, you lose context (which of the thr
by jjnoakes 10y ago
Yeah but you aren't really capturing the difference fully.
If all of the exception handling code is at the end of the block, you lose context (which of the three file opens the this FileNotFoundException), scope (every variable you want to use during cleanup has to be declared outside the try, initialized to a sentinel, and then checked in the catch to be sure the try initialized it to the real value), locality (the code, the error handling, and possibly the finally block all deal with the same things, and should be in sync, but are spread out), and more...
Error codes are verbose, but exceptions have issues to.
Neither one is ideal for me but error codes are the lesser of two evils for the time being.
- MereInterest 10y agoDepends on the language for me. If I'm in Java and need to put try-finally blocks for cleanup of non-memory resources, then error codes are cleaner. If I'm in C++, with all objects using RAII to clean up after themselves, then exceptions are the simple way to go.
- jjnoakes 10y agoEven with raii and exceptions, I find myself disliking exceptions. I like seeing which parts of my program can fail, and I want to be forced to consider what should happen in different failure scenarios. I like explicit error handling because not only is it obvious where my program can fail (and why), but it is obvious where it can't fail too. With exceptions, any line of code may fail. Or maybe not. It is all invisible. (Now this assumes a language that enforces return code checking; I use C and a static analysis pass today, but a few languages get this built-in).
- prodigal_erik 10y agotry-with-resources helps a lot, it basically invokes AutoCloseable.close for RAII-style cleanup.
- rdtsc 10y ago> you lose context Sometimes you don't care about the context. You can have middle-ware code: [top level code]<->[your code]<->[library]. Maybe you don't care if library throws a "disk full" exception or "network down", littering that part with "if err != nil ... " might not be the best solution. Top level code might decide to log the error, retry, retry and log, send a page, or even just let another layer on top of it decide. But as you say it is a trade-off. At lest Rust provides a neat try! macro, it goes a long way in handling boilerplate. let mut f = try!(File::open(filepath)); let a_byte = try!(f.read_u8()); Perhaps Go would provide a source code transformation tool, to automatically expand code to do the equivalent.