225 points · by ubershmekel · 14y ago · 239 comments
But I also think this is a very silly reason to adopt or not adopt a tool. No other approach to error handling is less fraught.
If Python is your only language, Go or something like Go is probably a very useful thing to have in your back pocket: compiled native binaries, fine-grained control over memory layout, and a simple and effective concurrency model is a good thing to have in one package.
There are a lot of things that annoy me about Go (and for that matter Python, which irritates me for very similar reasons). What I tell myself to get over that and keep an open mind is, Go may not be my idea of an elegant language (yet; I'm still learning to appreciate it), but it is an excellent tool. I can get over the language stuff if the tool works well enough, and Go seems to for me.
Incidentally, who "leaves" a language? I have a very hard time seeing how, even from the label on the tin, anyone could believe Go is a great solution for every problem. Python sure as hell isn't either.
I started programming almost 30 years ago. Some languages I haven't touched in decades: BASIC, Fortran or Pascal. These days every time I have to use Java I hope it's the last. On the other hand, I used C for the first time 25 years ago. I don't use it very often but I wouldn't say I've left it.
So yes, people leave languages. And in many cases for good reason.
Go isn't particularly elegant in my opinion, either, at least not compared to a lot of languages. But it's pretty good for getting stuff done, and handles a lot of common problems in a way that is direct and simple. I can perceive that utilitarianism as a form of elegance.
The thing that kills me about Go's error handling is you return error AND value all the time. It's like an Either that always has Left and Right. I think it's a bummer, especially coming from a group that has developed languages in the past.
CL's condition system is less fraught: http://www.gigamonkeys.com/book/beyond-exception-handling-co...
There are two general use cases for exceptions:
1. Unexpected (typically fatal) problems;
2. As an alternative to multiple return values.
(1) is things like out of memory errors. (2) is things like you're trying to parse a user input into a number and it fails. I despise (2) for exceptions. It means writing code like:
try:
f = float(someText)
catch ValueError:
# I just parsed you, this is crazy,
# here's an exception, throw it maybe?
where this gets particularly irritating is when you start writing code like this: try:
doSomething()
catch ValueError:
pass
I nearly always end up writing wrapper functions around that crap.Java is worse for this because some libraries (including standard ones) abuse checked exceptions for this. I actually prefer:
if f, err := strconv.ParseFloat(text); err != nil {
// do something
}
or even: f, _ := strconv.ParseFloat(text);
for this kind of scenario.For the truly bad--typically fatal--error conditions and cleanup, IMHO defer/panic actually works quite well. I certainly prefer this:
f := File.Open('foo')
defer f.Close()
// do stuff
to: try:
f = open('foo')
# do stuff
finally:
if f:
f.close()
as Go puts the two relevant things together.Don't get me wrong: I like Python too but I do think Go has a lot going for it and has a bright future.
If you're going to use return values to indicate errors (and certainly I feel that there are reasons to use them, exceptions vs error codes is not an either/or proposition IMO), you should use sum types and return either an error or the correct value and have a mechanism to make sure you handle both cases.
ML and Haskell get this right, it's a shame Go overlooked them in this regard.
Why would you even be interested in the float when there's an error?
But in order to live in peace you have to either:
* Force every programmer to always check all the error values.
or
* Allow errors to pass silently.
So either you accept Go as a heavy-duty, heavy boilerplate error handling laden language. Or you accept it as a flaky, risky language.
Exceptions are the better compromise in my opinion. You get much cleaner code.
If this is the more common pattern for your programming life:
try:
f = float(someText)
use_it_here(f)
use_it_there(f)
catch Exception:
# I wanted to do things, but something went wrong.
# Here's what to do now, this is easy
Then you're better off using exceptions. If you need to check every single call (e.g. NASA or Kernel programming) then you might prefer this: if f, err := strconv.ParseFloat(text); err != nil {
// do something
}
if f, err := use_it_here(text); err != nil {
// do something
}
if f, err := use_it_there(text); err != nil {
// do something
}Given this, I don't see how Go is any worse with respect to sloppy programmers. They'll Always Find A Way.
Also, why couldn't your second example be nested? It seems like either of those two examples could be structured identically to the other.
Errors should never pass silently
Unless explicitly silenced
The problem with go is that you have 3 error modes:1. Explicitly handle everything
2. Implicitly silence sometimes
3. Panic/recover explodes sometimes (who knows where/when?)
Mode #2 is dangerous.
Java/Python give you 2 only modes:
1. Implicitly explode on error.
2. Explicitly silence sometimes.
Where both modes aren't inherently dangerous, i.e. they won't directly cause undefined states to execute.
--------------------
Concerning the nesting in my examples - I'm used to the style of C programming where failing is mostly handled by a return as to keep the program as readable (and thus flat) as possible. So pardon my french but I assumed "// do something" would somehow prevent further usage of 'f'.
Note that the Go example, although tedious, isn't bad in cases where you really do need to check every single possible error.
You could certainly argue for handling each message in a separate process a la erlang, but this approach worked well for us.
I think checked exceptions were a mistake (IIRC Gosling agrees), and Java could do with better support for multiple return values (which exceptions get abused for), but I like Java-style runtime exceptions.
with open("x.txt") as f:
#do stuff with f
That's it. Obviously, compared to 'defer', it hides stuff - the actual magic happens in special methods __enter__ and __exit__ of the object passed to 'with'. def withSomeResource
handle = acquireSomeResource
yield handle
ensure
freeSomeResource(handle) if handle
end
withSomeResource do |h|
h.whatever
end
File.open and other parts of the standard library does that by default. I imagine the Python implementation of "with" is pretty similar, given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..": def with r
r.__enter__
yield(r)
ensure
r.__exit__
endPython's 'with' inverts the control - the control is with the language runtime and the resource is passive here. In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime. The resource itself (or the contextmanager representing it) only implements __enter__ and __exit__ and is passive with regards to this mechanism.
Note that there's a difference in the handling of exceptions: if an exception is triggered from the `with` block, it is intercepted, provided to __exit__ and can be silenced if needed or desired (by returning a truthy value). So a closer approximation would be:
def with r
r.__enter__
begin
yield(r)
rescue Exception => e
raise unless r.__exit__(e)
else
r.__exit__(nil)
end
endThen again, `f.Close()` could hide any "magic" you want as well.
try (FileInputStream f = new FileInputStream(path)) {
// do stuff
}No, you have it exactly backwards. It's with return values that you have to check after every call to be safe. With exceptions you can truly say: if I don't know what to do if this fails then I don't do anything. You can let the exception bubble up higher, all the way up to crashing the program if you like (which gives a nice stack trace that can then be debugged).
With return values, if you don't check then you could be building up more and more trash and you won't even know it until you either hit a point of code that finally does look at what's returned, or if an exception occurs (e.g. segfault).
try:
f = float(someText)
catch ValueError:
# I just parsed you, this is crazy,
# here's an exception, throw it maybe?
Formatted That For You with open('foo') as f:
# do stuffIf 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.
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.
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.)
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.
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.
I believe I'm correct as no one has yet refuted the central problem discussed. The replies have mainly been justifying it.
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.
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.
That's a bold statement. Nice to meet ya! I'm no PC-Luser! ;-)
The PC-lusering problem is mentioned in "worse is better", so I would hope a fair number of folks know about it. Every good code base I've seen uses EINTR wrappers, but it is true that many folks I've met don't know about it.
Hey now.. it's not just C programmers, though. We have to use the same EINTR-retry loops in python too, sometimes:
https://github.com/git-cola/git-cola/blob/master/cola/decora...
I like C, Python, and Go. There's no reason to take sides, IMO. These are all highly effective tools.
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.
(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".)
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.
It's very similar to exceptions, except you have to consciously choose to do it. That's a virtue to me.
Irrelevant with go, thanks to the `defer` statement.
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).
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.
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.
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; 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. func A() error {
return compute.Something()
} 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.But error handling is one of those topics that really gets people going. From ABEND in the old IBM batch days, to uncatchable signals like SEGV in unix and uncaught exceptions in C++ or Java.
I tend to come down on the "decide what you are going to do in the code, right where the error occurs" flavor of the argument. So checking for errors when they occur is important to me, what to do next gets to be sticky.
So there are three things you want to do:
1) Easy - you just want to quit/die/exit pretend you never existed. This is pretty easy and most OS'es and embedded toolkits have something along the lines of 'exit' or 'exit_with_dump.' So that later you can try to reconstruct what happened.
2) Is "this is bad, but it might be ok later" where you want to unwind to the point where this started but not completely exit. Exceptions are pretty good for this if used well since you can catch them at the 'unwind' point and if you can attach the unwinding actions (closing files, freeing memory, etc) to the return stack then it can be managable.
3) You want to plod along in a degraded mode, which means you need some way of communicating with the rest of your code that you're damaged goods at some level.
Go has an interesting mix which I haven't used extensively but I wouldn't dismiss it out of hand. The folks writing it run services that continue through partial outages so if it were too egregious folks would rebel inside of Google.
The culture of writing code, and that code being fine once a unit test is passing seems to propagate the myth that it's fine for any code to throw any exception at any time – it doesn't matter as long as those errors expected to occur from testing are the only conditions that ever occur. As for the rest, well. Kaboom!
Starting off from C, it doesn't take you more than your first 100 lines before you discover pain due to missing a return value. In my experience, eventually 60% of your time is spent wondering how this particular return value propagates throughout the rest of the code you've written, and libraries in use.
The end result is my C code tends to be much more robust in the face of braindamage (say, network errors, IO errors) than my Python, simply as a result of a cultural mindset that basically encourages ignorance of error conditions.
You can also trace one of the biggest pains from Python 2 back to this culture: deferred error handling is at the very core of the Unicode/strings mess, probably the single most motivating factor for moving to Python 3.
[Extremely tired, aware this is poorly written and sways between points, but hope it makes some sense]
SEGV can be caught. There are only 3 uncatchable signals: KILL, STOP and CONT.
2 and 3 I've found to be at little less verbose as there's no try {...} catch{...} around it.
It seems a nice way of avoiding the stack sentinels or setjmp/longjmp that C++ has, which means the output is less architecture dependent.
Personally I don't think Go is quite ready for prime time, but it's definitely promising. I'm doing a couple of projects with it to see how it runs.
Error handling is explicit, like the quote you quoted said it should be. If you ignore the returns (either explicitly or implicitly) you pay the price in debugging.
"leaving me confused as to which error happens when" Panics happen when something very bad happens. You shouldn't be accessing off the end of an array, it signals that you've probably programmed it incorrectly, rather than it being a problem with your input (~ish). Same with divide-by-zero and type assertions. However, they provide another control path that in a limited number of situations, can give elegant results.
Contrast that to other languages, such as python, where you don't ignore the errors because you know that if something goes wrong, an exception will be raised.
It lets you do stuff like:
def whatever(request): my_int = int(request.POST['some-param'])
Note that, in that case, we don't check if 'some-param' is in POST. Neither what happens if it's not a number.. Basically, an exception will be raised and a 404 will be shown.
I understand your point in general, but have to disagree with the example you chose. A 404 implies Page Not Found.
The Python framework I use (http://bottlepy.org/docs/0.9/_modules/bottle.html) makes this a 500 Internal Server Error, with the text "Critical error while processing request: /foo-bar". IMO, this is ugly, and not super user-friendly, so I usually end up writing try catches around "one-liners" to log a better error than a stack dump, and present a friendlier message.
If he really wants this kind of framework-provided error message, then a panic would be more appropriate, because the HTTP server in Go will do the same thing as bottle. It's definitely not going to be as succinct, but it'll be more succinct.
if err := datastore.Get(c, key, record); err != nil {
return &appError{err, "Record not found", 404}
}
This is pretty typical Google Go error handling, where errors are only actually used as boolean flags. Errors are universally returned as type 'error' so to actually do anything with the error you have to first cast it to some specific type. But that type isn't part of the method signature so you have to dig around in the source or, if you are very lucky, it was documented someplace. You end up having actual error handling plus even more error handling for if you got the error type wrong.For instance if datastore could return 'record not found' or 'io error' then they would usually be treated the same way by the code because to do otherwise would be even that more of a hassle.
err := datastore.Get(c, key, record)
if err == ErrNoSuchEntity {
// entity not found
return
} else if err != nil {
// some other error
return
}
Don't really see the hassle you are referring to. switch err.(type) {
case Type1:
// do something
case Type2:
// something different
default:
// something else
}This is quite correct and what's really broken with Go's approach to error handling and documentation.
For every language feature someone likes there's someone else who hates it, and vice-versa.
The point of the post is that Go doesn't give you the option, whereas Python let's you decide when and how you'll deal with it.
The proliferation of checked exceptions all throughout the code is a whole other ball of wax.
I appreciate Go because I'm working hard to become an engineer who builds robust software rather than a sloppy hacker that throws scripts together. One significant difference between the former and the latter is carefully handling errors versus not.
Python's error handling seems much more succinct only because most of us don't both handling errors at all! Every other line throws many exceptions, but we ignore this for convenience. (Those ugly "except ___:" statements ruin our oh-so-cool one-liners!)
Bottom line:
When I feel like having fun making something simple and getting it done _fast_, I use Python.
When I feel like building something that _needs_ to work -- especially anything that does more than one thing at a time, or should use all cores efficiently -- I use Go. And yes, that means taking error handling seriously.
There is such a thing as progress, and in my opinion the way you get it is by spending lots of time trying new things and seeing which ones work. So I'm in favor of "leaving a language that was working well for them just because of some hype."
You can try new things, but abandon the other ones because of hype (or thinking it's better cuz "ppl who don't know anything about languages said so") instead of true technical merit is pretty fucked up :)
Now then again Go ain't bad, but I don't see it being better enough than Python to switch in this case. Python in better for many things as well. Not a large step enough.
Garbage collection relieves you from the drudgery, accounting and bureaucracy of manual memory management and indirectly leads to more expressive forms of programming once function boundaries are freed from having to specify who owns the data being passed back and forth. But you still need to be aware of space vs time usage, you still need to know where memory is being allocated, used and kept alive in your program, and you can still have "leaks" where a data structure is rooting too much dead data. This isn't immediately obvious to the novice, but that isn't IMHO a good reason to dislike the "magic" behaviour of GC. In the hands of someone who knows what's going on, programs get much simpler.
Exceptions relieve you from the drudgery, accounting and bureaucracy of manual error passing and recovery, and indirectly leads to more expressive forms of programming once function boundaries are freed from having to specify how rich error conditions are passed back along the chain of callers. But you still need to be aware of errors that require aborting and errors that can be fixed and resumed. You can still ignore exceptions that leads to programs crashing when they shouldn't. Looking at a program using exception handling, it sometimes isn't immediately obvious to the novice how the exception plumbing is working (especially since you don't usually see it at the function call level), but that isn't IMHO a good reason to dislike the "magic" behaviour of exceptions. In the hands of someone who knows what's going on, programs get much simpler.
I never really got this argument. With RAII types that have value semantics (ala shared_ptr) what is so difficult about memory management in C++? I guess there are reference cycles, but weak_ptr can help there. Manual ref-counting (like a COM AddRef/Release pattern) can be tricky, but that is where attention to detail, code reviews and basic competence come in. RAII wrappers with value semantics help here too. Most problems I have seen with that have been people simply not bothering to learn even the basics or using "smart" objects without understanding how they work or how to use them properly, which really isn't that hard, honestly.
>that isn't IMHO a good reason to dislike the "magic" behaviour of exceptions.
Agreed, my primary pain point around exceptions is people that write functions that mutate some state and are interrupted in the middle via an exception and stack unwind leaves objects in some franken-state. Transactional semantics in the face of exceptions don't just happen except in trivial cases (i.e. functions that don't mutate state or have trivial unwind semantics where they must only restore say a single mutated value).
That said the same problem exists anytime there is state mutation and multiple, failure exit paths. For some reason I guess the code I have seen using error code return style tends to handle this better. Could just be some kind of selection bias.
In UI apps, it's much much harder to guarantee transactional semantics unless you're using persistent data structures or similar techniques that make in-memory transactions / undo trivial to make correct. So it makes more sense for exceptions there to save user data where possible, log the error (potentially back to the vendor), and restart the app.
(I don't want to talk about C++. I think both C++ exception handling and memory allocation are broken by C++'s design. You can only make it sort of work with coding standards, and even then it's labour intensive. If you don't yet understand why GC increases productivity, it's an epiphany you'll need to look forward to. Bonus: GC also makes exception safety far easier. For example, you can write a stack.pop() that returns the value popped - one of my favourite examples of C++ being broken.)
Oh I fully understand/agree with that, I just don't find C++ memory management to be too hard. The concurrency concerns pointed out by others are true, though. Whether they (the concerns) are offset by the lack of deterministic destruction and the extreme triviality of creating reference chains that root things far longer than needed due to the root being live while the rest of the chain should be dead, is another question.
As you pointed out, in some domains transactional code is fairly straightforward, or at least tractable without inducing massive depression. In some other domains, not so much :)
But more importantly, what makes C++ memory management difficult is that different libraries do it in completely different ways. Bridging that mess is error prone and a huge mental burden.
For me, C++ memory management becomes challenging in the face of concurrency. Particularly when you write applications that are event-driven, instead of thread-based, and you've surrendered to an event loop. It becomes challenging to keep track of object lifetimes.
Just my 2c.
The world is far more nuanced than that.
This is Go's mechanism for handling (or ignoring errors) which imho is really nice because you don't have to learn anything extra, like throwing/catching error mechanisms
If you were to handle the same error cases in Python that you gave examples for in Go, it would probably be even more verbose with the try/catch wrapped around.
> Errors passing silently – ticking time bombs to go
Are you kidding? Unless exceptions are documented well, which they rarely are, this is a much greater problem when using exceptions.
No it's not. If you get an exception you didn't prepare for, your code fails, not silently but very loudly. The argument to have is whether this is better or worse than your code silently continuing to do all the next steps even though the first one failed.
(FWIW I agree with the article, but will say it's kind of surprising to see that point of view from a python programmer given the python approach to type-checking)
try:
datastore.Get(c, key, record);
viewTemplate.Execute(w, record);
catch e: appError(e);Particularly: Haskell is fast, concurrent by design (whatever that means, I'm sure Haskell is :P), typed but not cumbersome or ugly (less cumbersome and ugly than Go's types, even) and--most importantly for this article--does error handling really well.
In a certain sense, Haskell's main method for handling errors is actually similar to Go's. It returns a type corresponding to either an error or a value (this type, naturally, is called Either). This method is special, oddly enough, because it isn't special: Either is just a normal Haskell type so the error checking isn't baked into the language.
Coming from another language, you would expect to have to check your return value each time. That is, you fear your code would look like this pseudocode:
if isError val1
then pass val1
else val2 <- someFunction val1
if isError val2
...
However, this is not the case! The people implementing Either noticed that this was a very common case: most of the time, you want to propagate an error value outwards and only do any work on a valid value. So you can actually just write code like this: do val1 <- someValue
val2 <- someFunction val1
val3 <- someFunction val2
someFunction val3
then, if any of the values return an error, it gets propagated to the end of the code. Then, when you want to check if you actually got a valid value--maybe in some central location in your code, or wherever is convenient--you can just use a normal case analysis.Additionally, while the errors do pass through essentially silently, the type checker does ensure you deal with them at some point before using or returning them. If you ever want to get the Int from a Either Error Int, you have to either handle the error case somehow or explicitly ignore it (e.g. with a partial pattern match). The latter option will generate a compiler warning, so you can't do it by accident without being notified.
So the mechanism is simple, but it can also stay out of your way syntactically. So what else is this good for? Well, it's just a normal data type, nothing special; you can use existing library functions with these values. For example, you can use the alternation operator <|> to find the first non-error value:
val1 <|> val2 <|> someFunction 5 <|> ...
This is often a very useful idiom which would be harder to write with a different way of handling errors. There are more utility functions like this (e.g. optional) that let you make your intents very clear at a high level. The optional function, for example, lets you do exactly what it claims: you can mark a value as "optional", meaning that any error from it will be ignored rather than propagated.You can also layer on this error-handling logic on other similar effects. For example, there are some types (like LogicT) that represent backtracking search. Combining error-handling with nondeterminism gives you a question: should an error cause the whole computation to fail, or only that particular branch? The beauty is that you can choose either option: if you wrap LogicT with ErrorT (this is just like Either except it can be combined with other types) an error will cause the whole computation to fail; if you wrap ErrorT with LogicT, the error will only cause the current branch to fail. This not only makes it easy to choose one or the other, but also makes it very clear which one you did choose: it's right there in the type system in a very declarative fashion.
Haskell also has a bunch of other advantages which aren't worth going into here. I think anybody looking for something like Go--a fast, high-level, concise, typed alternative to Python--should definitely consider Haskell. While it may not seem so at first, I believe that Go and Haskell are good for a very similar set of problems and so actually overlap quite a bit.
If you really dislike some particular things about Haskell, you should also consider some similar languages like OCaml and F#. I personally prefer Haskell, but there are definitely good cases to be made for either of the other two.
Haskell (IMHO) won't ever be mainstream for much the same reasons Lisp never was (or will be?): it has an incredibly high learning curve (eg [1]).
This is really the problem of the "pure" functional languages. Functional programming is suited to some tasks. With others the fit is almost tortuous. Imperative programming is well-suited to how we think and how we break down tasks.
If you look at the popular languages they're pretty much all multi-paradigm (eg Ruby, Python, Go, C#, arguably even C++/Java) meaning they give you the low-hanging fruit of functional programming while still being in a relative sweet spot of being easy to learn yet reasonably expressive.
Why I think Go has a very bright future ahead of it is that it is the first of these multi-paradigm language to combine all these features:
- easy to learn (seriously, go look at how short [2] is; you can knock that out in an afternoon);
- it is minimal. I LOVE Go's minimal OO model for example; and
- it is statically typed.
If you look at the other statically typed multi-paradigm languages you have C#, which is generally well-regarded... except (Mono notwithstanding) it is very Windows-centric. Java is, well, Java. C++ is incredibly complicated.
The only thing Go is missing is a mode for (semi-)manual memory management. I'm thinking something like Obj-C's ARC (in iOS 5+) and it could well supplant C/C++ for the vast majority of their (already shriking) use cases... eventually (Go has some work to do on speed).
[1]: http://stackoverflow.com/questions/377082/how-long-does-it-t...
Bingo. Anybody that thinks Haskell will ever escape its niche has not spent enough time working with rank & file programmers. That doesn't mean you shouldn't consider it or that it can't find a large enough niche to sustain itself but it does mean that it's unlikely to ever overcome what Carmack refers to as "externalities" for a lot of prospective users.
I love monads (I love arrows more, but that's another issue). I'm a language design geek. My level of expertise is different from someone who has just been hired into a new job and wants to get things done.
I suspect that most language designers know about monads - I'm not sure Rob Pike did, but it's pretty common knowledge among folks who do this stuff. Until you can explain them to the folks who'll be using the language in a way that doesn't make them seem like arcane black magic, though, you'll find programmers will just say "I don't get this" and use what they're familiar with.
As someone with 10+ years of programming experience in the industry but no formal college education, I see the problem with Haskell (and other, similar functional programming languages) that in order to fully understand the language, you need to understand its theoretical foundation. Same goes for monads, combinators, etc. Without understanding the theory they're based on, it's impossible to use them and also hard to read programs that employ them.
The theoretical foundation of Go on the other hand is much smaller, and way easier to understand, especially for people without a formal CS education.
So, yes, I admit that I don't "get" Haskell in all its glory, and I'm not ashamed of it because I know that most people in IT don't and that's why it will always remain relatively obscure even if its approaches to a number of programming language problems are technically and theoretically sound.
I have seen this (the error monad) mentioned before as a "nice" way of handling errors, even with explicit error returns. I beg to differ - the error messages produced by such a program will be obscure, as all the context is lost - if the first call to someFunction fails, for example, there's not necessarily any indication that the error came from that call rather than the one after it.
Go's explicit error handling means that it's easy to add meaningful context wherever relevant - the error messages printed by such a program are likely to be considerably more useful.
In the end, adding error checks is doing useful work. Each error case should be considered individually, and I've often found it to be the case that it's useful to treat errors as regular values (for example by collecting a bunch of errors, or returning the most important error only).
I can understand the control flow of a Go function by inspecting it on the page (without a glance at the documentation). That's a huge plus.
As for the error collecting bit I think Haskell can do that as well. Errors are just regular values in Haskell and its just a matter of not using do notation or using a diferent error monad if you want to create a list of errors instead of getting out when the first one occurs.
Ill have to agree with you on the control-flow at a glance issue though. This gets really tricky in Haskell, especially when you take lazy evaluation into account.
This is completely incorrect. If you use Maybe, then you get Just value or Nothing, in which case there is no indication of what error occurred. This is used when you don't want to consider what error occurred, simply that the computation failed. If you use Either, then you get an error or a value. The error obviously gives the context you are looking for.
For example, if I compile a binary on my Ubuntu machine and SCP it to a server running centOS Linux, the binary just fails to run because of shared lib issues.
Even if you try and compile the binary statically I still run into similar problems.
This is in stark contrast to any Go/D/C/C++ binary which works fine
ghc helloworld.hs -o helloworld
<scp binary and ssh to remote machine>
./helloworld
./helloworld: error while loading shared libraries: libgmp.so.10: cannot open shared object file: No such file or directory
However if I compile statically, I get a different error ghc helloworld.hs --make -optc-static -optl-static -optl-pthread -static -o helloworld
<scp binary and ssh to remote machine>
./helloworld
FATAL: kernel too old
Segmentation fault
This guy experiences similar issues.Different situations warrant different strategies. Sometimes it's ok to return NULL, sometimes it's ok to return true/false and pass the actual result back indirectly, sometimes it's ok to return the value but use an external error flag. Sometimes it's ok to mix control flow and external flagging of errors, namely what an exception is, effectively.
However, in my opinion, languages who point too much to one single error handling mechanism are more irritating than languages that leave it up to the programmer. I'm particularly wary of exceptions per se: they're a really nice, clean concept but on the other hand I rarely hit an use case that would be a perfect hit for exceptions, and even those perfect cases for exception-handling wouldn't look too shabby if designed with other error handling strategies.
On the other hand, many cases where errors are handled with exceptions get awfully ugly in the normal case. For example, the "try: ... except <name-of-error>: pass" idiom in Python. I can't count the number of times I've written a small wrapper function around a trivial exception handling case, that just flattens the result and error into a suitable value if that fits my use case.
I do not have the same rule for python.
I find Python's exceptions model to be something that does occasionally frustrate me. For example, I'm used to using NSIS for some things (the PortableApps.com Launcher being one thing); its model is that a command may set the global error flag. This means that some sorts of things will fail silently - occasionally bad, but generally good. Some styles of Python scripts (generally automation scripts rather than full-blown programs) would do much better ignoring most errors. When you have a script merrily chugging along and all of a sudden due to some obscure corner case (perhaps not even documented) in a small, incidental part of the script the whole thing quits, it can be rather annoying.
The Go approach lets you catch errors if you want, or drop them, much more easily than Python approach. My inclination at present is that the Go approach is more likely to end up with error-resilient code, as it encourages dealing with errors each time, while Python typically encourages you to let the caller deal with an exception if you can't - but often I think the caller doesn't realise that he should. Or after a couple of levels of indirection, it's not even documented that that exception can occur. (This sort of thing, I believe, is something that Java's checked exceptions were supposed to help with - either deal with the exception or declare it.)
For myself, I've had lots of experience with Python and am now dabbling with Go, using it for two smaller projects to decide which to use for my next major project. At the very least, I think the approach is worthwhile trying in a serious project that its merits and those of the Python approach may be more completely analysed.
Anyone want to fork Go?
Errors aren't the same things as exceptions.
I could see forking it to add generics in a way that the official guys aren't satisfied with, but why is that needed to use another style of error handling?
But so far I have not noticed anyone doing this, perhaps because actually returning and handling errors properly is not as much of an issue as most people make it to be.
The reasons not to that I have seen are all basically boil down to "Because you're not supposed to, it's not what it's for". Because of how recover works it certainly wouldn't make sense to use it exactly the same as try/catch is generally used, but what exactly would be the problem with using panic/recover for more common cases (less 'exceptional' cases...) if we've already decided to not value writing idiomatic code?
It strikes me as a terrible idea, but try/catch does too.. I guess I don't understand why it would be even worse than that.
Are we talking about just forking its standard library and not actually changing the language?
x, err := something()
if err != nil {
handleError(err)
}
n, err := somethingElse(x)
if err != nil {
handleError(err)
}
andSoOn()
you could write switch x := something() {
case error:
handleError(err)
case string:
switch n := somethingElse(x) {
case error:
handleError(n)
case int:
andSoOn()
}
}
? x := something()
n := somethingElse(x)
andSoOn()
no longer compiles.Obviously you would also want some syntactic sugar to make it look nice, but that's quite simple.
Once again the president has been saved, thanks to HTTP Pedantry.
I propose a new HTTP verb, MEH, to address the belief that the HTTP verb mechanism is unnecessary or over specified. The semantics of HTTP MEH are application-defined, so it can be used to fetch, update, replace, query, delete, or whatever the application defines to be necessary. Services honoring HTTP MEH implicitly signal that interoperability is not supported, but that intermediate proxies 'should do the right thing' regardless.
I struggled with this aspect of Go coding too and what I decided was that, in order to choose your approach to errors, you should think about how important it is that your function can be composed into an expression:
x := foo(a) + bar(b)
vs. c, err := foo(a)
if err != nil {
...
}
d, err := bar(b)
if err != nil {
...
}
x := c + d
It's a trade-off. By using "panic", you enable more concise and compositional code. By using error-returns, you are being more explicit and making it easier for the caller to handle errors at the call-site.Usually, functions that can fail are not the kind you desperately want to use in expressions anyway. So error-returns are more common. But there are many situations where errors can happen and where composition is a big win. In those cases, you reach for "panic".
If you look at some of the built-ins that can panic--I'm thinking of array-indexing and division and regexp.MustCompile(), for example--you notice that these would become very cumbersome if they used error-returns instead.
There's also the issue of initialization. That's the justification given in the case of regexp.MustCompile(). An initializer must be a single expression.
The words "panic" and "error" probably lead people to think that you should make the decision based on severity but I don't think that's right.
(That's just my take on it. I'm no Go expert so there are likely better ways to think about it.)
By contrast, a network timeout is not a disaster. It's not "normal" or desired behavior but it's well within widely-known modes of behavior.
Composition is nice-to-have but in general you ought to be able to write Go as if everything that does not return errors will succeed under the vast majority of circumstances, or where failure is inevitable.
Recover is, among other things, a failsafe of sorts for cases when code you do not control (e.g. a library) panics. It might be catastrophic failure for the library, but it may not be for your code, and you need an escape hatch.
...I am not an expert, either, but I've spent a fair amount of time on the Go mailing lists. I feel like I'm actually repeating something I've read, but Effective Go doesn't talk much about this. (It does say that library functions should avoid panic.)
Put another way: when you call an API correctly, it should be safe to assume it will never panic().
Panic/recover can be used in rare occasions within libraries to do more exception-ish style error handling, but those panics should never be allowed to escape and cross API boundaries.
x, err := *p
Where err is nil unless p is nil. And for array indexing: x, err := a[n]
The runtime could do its bounds check and return (zero, IndexOutOfBoundsError) if the check fails, where zero is the zero-value for the type. It seems to me that these solutions are perfectly workable except for the massive code-size/verbosity explosion they would induce.In such cases, the code should effectively prove that p is not nil and n is within bounds before performing the risky operations. Maybe a good plan is to always validate input first so that you can write expression-oriented code that only fails in the case of programmer error.
A situation from my experience was a recursive transformation where an intermediate call had no good way to deal with an error except pass it along to its caller--so I used a panic within the package for that. In hindsight, I think a better solution may have been to validate the input in an earlier pass so that the recursive transformation should always succeed.
So, in cases where the program can validate inputs first, it should do so and then be free to use compositional code that panics when the validation was broken. In cases where validation cannot remove error conditions, error-returns should be used.
Reserving panic for programmer-error, as luriel recommends in his reply, seems like a good maxim. I think I'll try to use that from now on.
>This is one of the things I can’t stand in C.
Having to check error values for every function call is indeed a pain. But C has macros and I think it is a nice and elegant way to handle errors. I personally prefer MACROS to exceptions when writing C/C++ code. But to each his own.
Does anyone know if go supports macros ? If they do not, it is one ugly problem to have!
EDIT I just realized you can write custom exceptions that can provide similar information about line numbers, functions etc. So removed a line saying that was a plus for macros.
Really the two styles of error communication are very similar. The default behavior for exceptions is to abort and let the parent deal with it, but you have the option of continuing on instead (catch). The default behavior for returned errors is to keep going, but you have the option of aborting and informing the caller. In either case you have to examine the code you're calling or its documentation to find out the details of what could happen when things go wrong.
Exceptions have the advantage of the abort-behavior requiring zero code, but it may be less obvious to beginners what is going on. In either case, people just don't like to be surprised, so they prefer what is familiar.
In C#, which has Tasks for concurrency (very similar to goroutines), an uncaught exception in a Task will bring down the entire program at some non-deterministic time, unless you make sure to observe it somewhere. So generally you're using some extension method so that invoking doSomething() in a Task looks like:
Task.Factory.StartNew(() => { doSomething(); }).OnException((ex) => { /*log it*/ });
Either that or you just make sure to catch anything at the root of your Task block.Called "conditions", fwiw. Smalltalk has a very similar system (the main difference is in the declaration of restarts)
Python 2 is fine, and the upgrade will offer few significant advantages for most people.
I think the effort would be better spent working on things like frameworks and tools for web development.
* It's really slow. * Most people write their code statically, but it's dynamically typed language anyway. * Things like '__init__'... what? * Having something you can see (whitespace) be significant is a bad idea. * Even worse, the community likes to use spaces instead of tabs, which makes the 'significant whitespace' a significant problem. * With the exception of Flask, important design patterns and lessons: DRY, SOC, DI, SRP, etc are largely ignored and called "Java-like."
Anyway, that's my $0.02
Sure, python is dynamic; at the time it was first created it was hard to provide the level of flexible ("duck") typing python has in a static environment. Now that typing has advanced, we are starting to see some level of type annotation support in python; I would expect it to get static typing eventually, but we can't break existing code. Still, I can totally understand leaving python for a static language with good type inference, like haskell or scala. I don't think go's type system is powerful or elegant enough though.
__init__ is fantastic; it removes all the special cases around constructors you see in other languages, and makes it "just another method" that follows all the usual method resolution rules etc. This means less to learn, less to bite you, and much easier to e.g. refactor a constructor into a factory method (or vice versa).
Whitespace isn't significant, indentation is. And when you look at a piece of code, you can see the indentation far more quickly and easily than you can see the braces. At least I can.
DRY, SOC, SRP are very much part of the python philosophy. I find python's standard library is much better at following "tell, don't ask" than most languages'. I agree that many python programs should follow the DI principle better and possibly the language should have better support for it, but IME the java/spring-approach as it's usually implemented doesn't really provide DI, it's just a complex reimplementation of singletons. I've yet to see a language or framework that can really help programmers do DI right if they don't already know.
The idea is quite simple: errors are not some rare special cases, they are ordinary, general events.
That means there are no need to some special mechanism for handling them. They should be handled as ordinary events within common FSM.
There is no contradiction in using the general mechanism of examining returned values to determine the state of procedure execution.
Any FSM requires if (or cond) statements. It is the essence of a program's logic.
The mechanism of exceptions was wrong. It is wrong in Java, it is wrong in C++. It is just a bad design.
The good design is using the same mechanism the underlying OS uses. In case of UNIX-derivatives it is the explicit checking of a return value. Because errors are common and ordinary events.
Amateurs believe that errors are rare, and they will avoid them. This is over-optimistic - in practice errors are of nothing special. It is just an alternative branch of a condition, where a consequent assumed to be a success.
Maybe a better error handling mechanism is needed - but I'd prefer if it's not exception handling. Perhaps lisp style error handling? What ever that is - for I'm not familiar with it - but I keep hearing lispers brag about how awesome it is!
Think exceptions, but instead of blowing away the stack on the way up to your exception handler, it gives you the option of resuming execution in some way where you left off. It also lets you encapsulate error handling better.
There are actually several nice things about the CL system, but nothing there is going to convince someone that actually thinks not only that having every return value in your language serve the role of an error signal is reasonable, but actually arguing that it is equivalent from a programmers perspective or even a better method of programming.