7 ms·
If you use a language that uses error codes, then you're forced to explicitly think about what to do in every single error case (or not, and accept the conseque
by crazygringo 14y ago
If you use a language that uses error codes, then you're forced to explicitly think about what to do in every single error case (or not, and accept the consequences). This can add a lot of mental overhead, but can result in a much more robust and well-thought-out program. But because more logic is involved period (to handle the robustness), the program is necessarily more complex.
If you use exception handling, then suddenly catching errors becomes much easier, and writing code is faster, but it's not like your program is any more robust. If you catch an error up at the top, your program or function is probably just going to quit. Of course, you can add more code to deal individually with each of the exceptions in more robust ways, even to the point of wrapping each statement in its own try/catch block, but then it's no different in practice from returning error codes.
In the end, I just don't see much of a practical difference. In both cases, if you want to be a lazy or rapid programmer, errors will lead to your software just not working. And if you want to be conscientious about your errors, then you can do that in both cases.
Exception handling lets you handle errors "at a distance". It's convenient, but harder to keep track of. Returning errors keeps your code execution where you can see it, and you always know where it is. It's simpler, but more verbose.
- babarock 14y agoPossibly relevant: http://www.tratt.net/laurie/tech_articles/articles/a_proposal_for_error_handling http://www.tratt.net/laurie/tech_articles/articles/a_proposa...
- belorn 14y agoI would guess that most (99%) of C programmers are lazy or has an rapid programming style then. Its a rare thing to see C source code that even do the simple thing like wrapping every write/read/print call with a loop that detects eintr. In my years of programming, I have yet to stumble on a other programer who even knows that one should be doing this. Looking at c libraries and their example code, almost every time, the example lacks error handling. Its almost like people avoid doing error checking in C code because of the cumbersome amount needed to be done in order to check each and every time. If an example code would include error checking, the number of lines can easy increase 3-4 times the original size.
- ams6110 14y agoTo be fair, most sample code I've seen, regardless of language, usually does not include error handling. Why not? Probably because it would detract from the main point being illustrated.
- xal 14y agoThat's true but also C's error reporting differs greatly between libraries. Each library has a learning curve in how it wants it's errors checked. From the top of my head, 10 years after writing any C code there is check against NULL - guess the error, check against minus values - lookup minus values in a table, check against 0 - call method to get error string and many more. Go standardises this in a super clean way. Every method that can error will return an error. If you try to write a method that calls methods that can error and you don't return an error then you will be extremely aware of that. After a few days of Go it will be physically painful to write code that eats errors. So what Go did was to take the return parameter style of error reporting, mix in multiple return values to make that not suck and then optimize towards the local maxima of programming comfort within this paradigm. The result - as anyone who has been writing go for a few months can tell you - is something that works incredibly well. I'd say it works better then exceptions style all but that may be my personal preference.
- slurgfest 14y agoI don't doubt that Go is usable and reflects an attempt to rationalize C's (non) conventions, which is a goal I appreciate. but it certainly isn't false for Python that 'the result - as anyone who has been writing [Python] for a few months can tell you - is something that works incredibly well.'
- kisielk 14y agoIn Go if you use the return value of a function you must also assign the error to something, either a variable or explicitly ignore it by assigning it to _. It was designed this way specifically to avoid the problem of not checking error conditions in C code.
- 14y ago
- JulianMorrison 14y agoThe following illustrates how you use Go errors as if they were exceptions: func A() error { err := compute.Something() if err != nil { return err } return nil } Throwing errors up the return chain using error values is really very little different than throwing up the return chain using exceptions, except that now there is only one way to return, and it is always clearly marked. You return where you say "return". And you return what you said you would.
- smosher 14y agoWhat am I missing here? This appears to be fully in-band and contains a redundant code path (constituting a NaN bug in languages with incomparable NaN—no idea if that applies to Go) for no apparent reason.
- JulianMorrison 14y agoWhat you're missing is that I'm showing how error throwing and error returning are functionally the same, when you have a standard error type, multiple valued return, and an idiom of returning errors you chose not to handle.
- smosher 14y agoSure, you can handle errors and you can explicitly pass the buck. That's no different than what we do in C. Exceptions are out-of-band (from a regular return value), and what you're talking about is entirely in-band. What you're doing, functionally, is returning a tuple. This is as old as the sun and nothing at all like exceptions. I'm not sure what you think idiom means (Hello, my name is Inigo Montoya), but you never need one to do anything in code. In human language they capture some context and their meaning must be understood by rote or in terms of that context, but in code they are entirely explicit and work just as well before and after becoming idiomatic—which is solely a form of classification that people use and computers don't.
- JulianMorrison 14y ago
- Sidnicious 14y agoThe default behavior for an error in a programing language with exceptions is to crash. This gets your program back to a known state (i.e. not running). It's impossible for code to blindly continue when something bad happens. If you want to handle some error in a way other than crashing, handle it. Web frameworks usually catch exceptions that arise while a request is being handled, finish the request, and keep handling new requests. You handle things more specifically only as needed. I like that behavior so much more than having a program keep running in an unknown state unless you handle errors line by line (and value it more than keeping code execution where I can see it). I don't think my programming language knows what errors are very important, either — that depends way too much on context.
- dmpk2k 14y agoI don't know about Go, but lint is commonly used to enforce checking of return values in C. Presumably Go could bake an option into the compiler to enforce this too.
- luriel 14y agoIn Go unused variables are an error, so you are forced to either handle errors or explicitly ignore them (by assigning them to _).
- Djehngo 14y agoSort of, you can actually get away with invoking a function and not assigning its result at all I think assigning the error to _ is only necassary when you have multiple return values(one of which is the error) and you are interested in at least one of them. e.g. returnsTwoValues() is legal x := returnsTwoValues() is not maps are also interesting because value := someMap[key] is valid and value, keyIsPresent := someMap[key] is also valid.
- stcredzero 14y ago> The default behavior for an error in a programing language with exceptions is to crash. This gets your program back to a known state (i.e. not running). It's impossible for code to blindly continue when something bad happens. In Smalltalk, the default behavior for an error is pretty much business as usual, because exception handling is mostly just Smalltalk code running normally. In some Smalltalks, you can override the "top level handler" and ensure that an app never crashes. (An infinitely growing collection will exhaust heap and crash the program that way.)
- jimbokun 14y ago"Of course, you can add more code to deal individually with each of the exceptions in more robust ways, even to the point of wrapping each statement in its own try/catch block, but then it's no different in practice from returning error codes." It is very different. With a try/catch block, you can see the normal logic flow of your code in one place, separated from the error handling logic. If you wrap each and every line that can have an exception with it's own try/catch block, then yes, that is pretty much the same as handling explicit error codes. Which is why I consider that poor style in languages that have exceptions. Separating error handling code apart from the logic flow of normal operation is simply not possible with error codes as function return values.
- to3m 14y agoUm... errors ARE normal operation. Consult historical output from your C++ compiler, if you don't believe me! (If anything, that should probably be "errors", quotes included, because what people usually mean by the term is "easily-forseeable occurrence that I couldn't be bothered to write the code for".)
- barrkel 14y agoCompiler errors aren't usually implemented as exceptions because compilers these days don't stop at the first error. Exceptions are ideal for things that require aborting and unwinding to a point - usually a loop, like a server request handler or UI event dispatcher - high up on the stack. If the general behaviour is not to abort and unwind, it's not a good fit for an exception. It's also why exception handlers should be very rare. There shouldn't be any more than a half-dozen in most programs. Error codes that need checking and aborting by hand at every function call boundary are a poor fit for replacing exceptions, because they optimize for the case where the error can be handled, rather than the usual case for exceptions, where the error cannot be handled.
- stcredzero 14y ago> Error codes that need checking and aborting by hand at every function call boundary are a poor fit for replacing exceptions, because they optimize for the case where the error can be handled, rather than the usual case for exceptions, where the error cannot be handled. From what I understand, the Go language team wanted to write robust servers, thus they wanted to "optimize for the case where the error can be handled."
- wonderzombie 14y agoI basically agree with you. I think return codes are simpler, and exceptions appear simpler because we're used to them. In reality they are a magical, out-of-band mechanism compared to plain old return. I contend that local and explicit is more strongly correlated with simplicity than remote and implicit. Put another way, verbose code can be simpler if it is direct and explicit — what happens is what's on the page — just as succinct code can be more complex if it is magical or implicit — what actually happens depends on who is calling it, say.
- slurgfest 14y agoI used return codes before I ever used exceptions, and even chafed at exceptions. Exceptions CAN be simpler. It's just an expressive tool, it matters more what you do with it. I do hate to read code which uses exceptions as a normal part of program flow, it's very GOTO-like and remote and implicit. But I don't write code that way and nothing is forcing me to write code that way. When exceptions are reserved for really exceptional conditions where a requested performance CANNOT continue, they are used much less frequently, and more locally and explicitly. In short I think the problem is a matter of philosophy more than language facilities, and the big differences are within-language rather than between-language. The reason I like to have exceptions used as a convention is that I think a better default for programs which have not yet covered some corner case is for them to decline to run, rather than to run in dishonor.
- mercurial 14y agoSay you need to migrate a database to a new schema. You need 10 SQL statements to do this. Each statement may fail, in which case you want to write stuff in a log and abort the transaction. In this case, wouldn't you agree that writing your statements in a try/catch/finally block would result in clean, easy to understand code, as opposed to adding explicit error handling after each statement?
- acqq 14y agoI wouldn't agree, as when I'd code it in C I'd have a function callSql which returns false and write the code you describe as: if ( callSql( s1 ) && callSql( s2 ) && callSql( s3 ) && callSql( s4 ) && callSql( s5 ) && callSql( s6 ) && callSql( s7 ) && callSql( s8 ) && callSql( s9 ) && callSql( s10 ) ) { endTransaction(); return true; } logAndAbortTransaction(); return false; No need for exceptions at all, and it's very clean and clear what's going on. I wrote the same code to my young exceptions-indoctrinated colleague who asked the same thing like you, and he couldn't believe at the start that that's all -- that much he wasn't used to a plain control flow. It's even obvious how it can be generalized for any sequence of commands: for ( int i = 0; i < n; i++ ) { if ( !callSql( s[ i ] ) { logAndAbortTransaction(); return false; } } endTransaction(); return true;
- hmart 14y agoJoel Spolsky on exceptions : http://www.joelonsoftware.com/items/2003/10/13.html http://www.joelonsoftware.com/items/2003/10/13.html
- hasenj 14y ago> They create too many possible exit points Irrelevant with go, thanks to the `defer` statement.
- makmanalp 14y agoOr, ya know, you just do: if (!herp_derp()){ ... } or if (herp_derp() > 0){ ... } and don't actually check any of the error cases that you should be checking, like return = -1, -2, -3 etc.
- slurgfest 14y agoI certainly agree that if you are thinking carefully about the code, either way should work just fine. As someone who likes C and Python I understand that both ways can make robust software, and it took me a little time to accept exceptions at all. More broadly, most of the languages that are widely used can write decent software. I think this is a matter of what you prefer the program to do by default, when something clearly wrong has happened, but no error-handling code has been written: you may prefer such code to halt, or you may prefer it to keep on trucking. If you use exceptions, you have to think about it IF you want the program to keep on trucking. Otherwise you can just let exceptional circumstances take care of themselves - if the program stops immediately, it cannot then behave incorrectly. As a default failure mode, I do prefer the program to halt and decline to further cock up the situation (forcing me and my tests to deal with the condition) than for the program to silently swallow the error and continue as a default (forcing me to thoroughly check error codes everywhere up front out of pure fear that I will miss a condition). This is just a convention and either one works. If Go can become a better version of C then I might switch out C for Go. This isn't by any means going to cause me to give up Python because I use C for very specific reasons (when it is totally OK for reasons of speed or control to write a decent amount more code, and have it read more cryptically, and have to take care of many more low-level details).
- wpietri 14y agoThe difference for me is whether I'm trying to reduce MTBF (mean time between failures) or MTTR (mean time to recovery). I'm in the first mode when I'm writing high-quality code to solve stable, well-understood problems. I'm in the latter when I'm doing almost anything else. E.g., prototyping, exploring, pushing out a MVP for user testing, adding a quick-and-dirty version of a feature to get real-world feedback. In the latter mode, I'm very tolerant of errors just as long as I can diagnose the problem quickly. The way I start is to catch exceptions at a very high level, tell the user something nice, and have myself paged. If something blows up, I fix it quickly. There's no sense in making code robust if I don't know if it will exist next week. Basically, the two approaches are the same only if you have infinite time and money. Google does, so I guess Go makes sense for them. But if this fellow's take is correct, Go's much less interesting to me as a general-purpose language.
- ubershmekel 14y agoVery nice point, right on the money. I believe I'm correct as no one has yet refuted the central problem discussed. The replies have mainly been justifying it.
- hntester123 14y agoThat's an interesting idea: to only catch exceptions at a very high level (for fast prototyping). I tried it out with this test program: http://pastie.org/4791686 http://pastie.org/4791686 Though it works, one potential issue I found with it is that it does not give enough context as to where in the program the exception occurred. E.g. if I have more than one open() call (all for read mode) in the code, it will give the same error message for an exception occurring on any of those open() calls (as long as the exceptions all happen for the same underlying reason, such as "file not found". E.g.: Exception occurred: IOError(2, 'No such file or directory') Had you come across this and found any way to handle it? I though of passing some unique code for each case, but there seems to be no way to do it, because we are not calling the except clause ourselves - Python does it. Edit: just thought of a (crude) way to handle that issue: declare a global variable, say, "location", and set it to a different numeric or string value at each place in the code where an exception may be thrown, or at least at one place, say the top of the function, in each function or method. And then in the single except clause, print the value: print "location=", location This will at least help narrow down the area of code in which the exception was thrown.