Go is a systems programming language, and a large part of systems programming is dealing with the potential errors. Take a look at, say, how the Linux kernel implements a system call. In fact, this is do_mmap_pgoff(), which does the bulk of the work for a mmap() system call in Linux: http://lxr.linux.no/linux+v3.1.1/mm/mmap.c#L942
It's almost nothing but error checking, and I submit that is as intended. In this circumstance, you want all of the error checking right in front of you, because that error checking is enforcing very important kernel policy. A lot of kernel code is error checking, because it has a lot of policy to enforce.
You're right that this error checking paradigm is a throwback to C, but Go was designed as a better C. Go's means of handling errors is exactly what I wish I could do in C; it allows every function to both return a value and an error code. It avoids passing in pointer to values because the function returns an error code, or having to check a global errno because the function returns a meaningful value. It's kinda like living in a world where C++, Java and Objective-C were never invented. (I like and use C++, so please don't take that as jumping on the C++-is-the-worst-thing-ever bandwagon.) I find that a very interesting direction, one which should be explored.
I use exceptions for higher-level code. When writing, say, a parser, I'd rather throw and catch exceptions. I don't think we need to choose one error-catching paradigm and declare it's best for all levels of code.
Which is also possible in Go, and template parser from its standard library is, actually, written in this style:
http://golang.org/src/pkg/template/parse/parse.go#L96
Functions call panic() (via t.errorf) to avoid passing errors between multiple levels of functions, but then Parse method catches it with recover(), checks what kind of error it is, and either panics again if it's a runtime error, or returns other kinds of errors.
Errors as return values force you to think about every possible error, which is a good thing for code quality. Look at how much rock stable C software we have out there. Software that can be compiled on many different architectures, run in many different environments, and it all just works, even 20 years later.
Writing code with try/catch is much less work. Not because you have to do less typing, but because you simply think less about how errors should be handled.
So my code hasn't had every possible failure case thought through and explicitly handled in advance. That's good. Firstly some of those errors are so rare they'll almost certainly never occur in my program's lifetime; by not having to handle them explicitly and individually I save time and money. Secondly I can guarantee that, no matter how good I think I am, the program will eventually find a way of crashing I'd not considered; this approach gives me a clean means of handling unforeseen errors as well.
A bad programmer can write bad code in any pattern and with any tools. A bad C programmer using return values can create so many different standards for how to handle errors that you might as well get out the divining rods to read the code. Personally, done right (as with anything) I happen to like try...catch.
For instance, a system might have plug-ins that get data from a CSV file, a relational database and a web service. One day somebody comes along and adds a plug-in that gets data from a noSQL database.
Add a new component to the system and you introduce not only new failure modes but new ways failure impacts the "system a s a whole."
The more decisions you make, the more you will make wrong decisions. Exceptions provide a reasonable default behavior that is "decision free" and reasonable ways to upgrade it.
20 year old C software lived in a simpler world; only specialized network utilities like telnet and tcpwrappers would have to face the consequences of a failing DNS lookup or the temporarily failure of a network switch in Toledo.
In fact, I think you can argue that keeping error-handling local to the call site (return codes) encapsulates and abstracts the errors better than letting an exception propagate arbitrarily far up the stack.
Exceptions are decision-free, but not making a decision (propagating an exception without handling it) doesn't make you any more robust to the vagaries of the modern world, it just moves the problem somewhere else.
Now, if multiple children in a call graph can experience the same error, and should be dealt with in exactly the same way, then propagating an exception up to a common ancestor in the call graph makes your code simpler. The fact that the compiler writes that dumb plumbing code for you is a great argument for exceptions, but not all applications fit the use case of:
* Same error can manifest itself in many places
* Each instance of the error can be dealt with in a similar-enough way to make a common exception handler simpler than handling errors at each call site.
Edit: Oh, did you mean that if you don't intend to handle an error, exceptions crash your program (good) rather than let it continue silently and do something you don't expect (bad)? If so, good point, and my apologies for the misunderstanding :)Which would be what exactly. The work of Knuth and djb I'll grant you, but the rest?
Care to try again?
iptables: Unknown error 4294967295
This wouldn't happen with exceptions - even if not handled properly, you'd see where is it originating and what's the most probable cause of the issue. And it's not necessarily iptable's fault - in some cases you have to really bend some rules to get the error you want. Also you cannot stack them so if you fail to cleanup after the original error, what do you return? The first or the second error? One has to be ignored.Fair enough, you'd rather (as a human being) have the second one. As a matter of building the system, I would still return the first one.
Basically, the second information is important in the sense that you really want an audit trail, but unimportant in that it doesn't tell you why your call failed. Returning it to the caller is useless compared to returning the first error.
But yes, it should certainly be logged and potentially acted on. An application can't do anything useful with the information, but an ops guy can.
So return the first one.
I know it's kind of unhip right now, but I would argue that what you're asking for is better handled using checked exceptions. That really forces you to think about error conditions, and it's enforced by the language. I'm continuously baffled by the argument that this is a bad idea.
I cant speak for Go but Scala's Option type is very different from C error codes since it is a monad. As a result you can use it with Scala's 'for' comprehensions (which are roughly the same as Haskell's arrows) and write code that looks roughly imperative without having to explicitly handle any errors.
http://www.scala-lang.org/api/current/index.html#scala.Optio...
> Many programmers in many situations would be perfectly happy to catch "failure to open a file" and "failure to open a database connection" and "failure to connect to a network host" with one simple handler that logs the failure and either aborts, retries or ignores.
aren't exception appropriate a according to a certain portion of developers. The reason they aren't exception appropriate is that you should expect these things to happen from time to time, ie they are not exceptional.
using exceptions to handle them is part of the problem Go attempts to solve by having multiple return values.
Either way it doesn't address the real argument, about where it is appropriate to use try and catch. What is inherently better about multiple return values at every level, compared to semi-centralized catch blocks?
Burying that kind of every-day, expected-circumstance logic in a side channel is, at least in some developers opinions, detrimental to the readability and understandability of a program.
My point was that there is a school of htought that exceptions should only be used in "exceptional" circumstances.
The examples given were not exceptional in that a programmer should expect those types of errors during the normal execution of their program. Therefor exceptions aren't the solution to those types of errors.
Does that make more sense to you?
PaulHoule is explaining why he likes a specific mechanism compared to another, and you are only replying with the previously-established fact that there exists a disagreement here, not a counterargument.
And I think alot of people take my point of view as evidenced by the votes my initial post received.
No worries, thanks for the point of view:)
I am probably one of those people who catches exceptions prematurely and who hasn't learned to use "finally." If you link to some advice on how to use such things, I'll read it. I want to believe that I can learn a better way to use exceptions, but they just haven't clicked for me.
Then again, I've been using exceptions in an environment (C#) that matches the author's JSON.parse() example very well. The .NET library designers already decided what counts as exceptional, and it's often not possible for me, as a .NET user, to decide much of anything about the use or placement of try/catch.
...when you're building real systems, the complexity of the error handling can approach or exceed the complexity of the "normal" path...
I can understand all too well that a complex error handling path is intimidating, tedious, distasteful, and no fun at all. But in every serious project I've been a part of, error and exception handling has been where the bulk of the design, implementation, and testing work was done. That stuff is precisely how serious systems distinguish themselves from toys. Having a catch-all crash-path doesn't change that, because the serious system is not permitted to crash. As the author here points out, that's what assert() has offered for decades anyway.
What do you mean? You can certainly decide what's exceptional. You can roll your own exceptions. You can catch and discard or handle exceptions you don't want to bubble up. You can put try-catch everywhere or nowhere (or choose a reasonable place in between). Your hands are not tied by .net exceptions any more than they are tied by any other reasonable error handling model.
I can decide to make something in my code exceptional, sure. I can't decide to make something in the library not-exceptional, though.
You can put try-catch everywhere or nowhere (or choose a reasonable place in between).
This isn't always the case. Sometimes the only way to answer a question ("Can this string be parsed as an integer?") is to try it and catch the exception. And there's just no way to do that coherently without catching it immediately.
Later releases of .NET do include a non-exception-throwing TryParse() call in many places. I'm pretty sure I've run into some cases where that was not available, however, and I'm pretty sure I've run into similar situations in other methods besides Parse(). And TryParse() was a late addition; look back in the 1.1 or 2.0 docs, and it doesn't exist.
In other words, somebody thought it was reasonable to force .NET users to catch some exceptions immediately.
Your hands are not tied by .net exceptions...
No, but there's not much point in using .NET if I'm not using the library that comes with it. And the design of the library does tie my hands in some cases.
I think the author makes a great point about libraries that use exception handling blurring the line between bugs and expected problems. That's exactly how I feel about the C# work I've done.
Making something in the library non-exceptional is equivalent to discarding an error. Catch the exception and discard it. Done. Do this at whatever level you feel is appropriate (or don't, and handle the exception in a more reasonable fashion).
> In other words, somebody thought it was reasonable to force .NET users to catch some exceptions immediately.
What do you suppose should be done? The other option seems to be to continue in a erroneous state. I'm probably not familiar with every possible error-handling methodology, but it seems the main ones are "error codes" (those worked so great in C, right), "exceptions" (annoying, but error handling in general is annoying), and "injected handling" (where the caller can inject error handling code somehow; but this is more complicated and requires deeper knowledge about the callee). Is there a better option?
> No, but there's not much point in using .NET if I'm not using the library that comes with it. And the design of the library does tie my hands in some cases.
My point is that you are not tied by .Net any more than you are tied by any other exception-handling language. You can handle exceptions where and how you feel is appropriate.
> I think the author makes a great point about libraries that use exception handling blurring the line between bugs and expected problems. That's exactly how I feel about the C# work I've done.
I think this is a bit of a red herring. An exceptional condition is simply a special case. A bug in the code is an exceptional condition. A problem parsing a number is an exceptional condition. Modern languages generally have specific exceptions to allow you to handle different situations with custom logic, but it's important to note that the runtime can't reliably distinguish between "bugs" and "expected problems". Did your number parsing fail because the user entered an invalid value or because your code grabbed column 3 instead of 4?
I guess this is where we differ. I feel that the designers of the .NET library have chosen to throw exceptions in places where nothing exceptional is actually happening, where no error has occurred, where the programmer may very well be expecting the "exceptional" outcome.
Where my code must handle such conditions, forcing me to handle them as exceptions makes my code longer, less readable, harder to change, and harder to reason about.
...it's important to note that the runtime can't reliably distinguish between "bugs" and "expected problems".
This is exactly what the author of the linked piece points out, this is a part of my complaint, and it's an issue Microsoft has tacitly acknowledged the seriousness of by the addition of alternatives to exception-throwing calls, like TryParse().
The problem from my perspective isn't the runtime or the languages that target it, but choices made when the library was designed.
It does not feel to me, as a user of these massive libraries, that there was any systematic way of deciding what should be and what should not be reported as an exception.
When does this actually happen? Are you really expecting it to fail when you open a file, or when you parse an integer, or whatever else? Where is .Net throwing exceptions in cases that no error has occurred and that you expect?
This complaint is common, but it feels rather hollow to me. Most of the time it seems to come down to a preference for error codes over exceptions, or an annoyance with the try-catch boilerplate, rather than a legitimate complaint about exceptions being thrown inappropriately.
> Where my code must handle such conditions, forcing me to handle them as exceptions makes my code longer, less readable, harder to change, and harder to reason about.
Are you suggesting that every function should have two versions like Parse and TryParse? Is this really what you'd prefer the .Net team work on, instead of providing new tools and functionality? Or are you wanting something like "ON ERROR RESUME NEXT" so that you can ignore these "expected" errors?
> This is exactly what the author of the linked piece points out, this is a part of my complaint, and it's an issue Microsoft has tacitly acknowledged the seriousness of by the addition of alternatives to exception-throwing calls, like TryParse().
Eh, the linked piece seemed mostly to be pining for the days of error codes. There's no general way to determine if a failure is a "bug" or "expected", not for exceptions and not for anything else. If you want to avoid exceptions for "expected" failures, then you're asking for no exceptions at all, which is fine, but the problem isn't just the definition of "exceptional".
> It does not feel to me, as a user of these massive libraries, that there was any systematic way of deciding what should be and what should not be reported as an exception.
The systematic way was "it's exceptional if it's not the desired or expected outcome". The addition of TryParse was a nice bonus, but is in itself an exception to the exception model.
Oh, for Pete's sake. I'm not learning what I hoped to here, and you've made up your mind.
Can you give me a practical situation where an exception is thrown despite there not being an error, aside from the canonical Integer.Parse() example? In my experience, that's not the bulk of any practical program, and it's still exceptional from the point of view of the Parse function.
I'd be interested in discussing this, but I'm not really sure what you think would be an improvement. And yes, it's a rather uphill battle if your proposal is to use error codes most of the time. I think that ship already sailed (although there's a strong case for error codes in C++, but that's kind of a special case).
System.ComponentModel.Win32Exception: The operation completed successfully at System.Drawing.BufferedGraphicsContext.CreateCompatibleDIB(IntPtr hdc, IntPtr hpal, Int32 ulWidth, Int32 ulHeight, IntPtr& ppvBits)
However, in the interest of trying to be helpful, my guess is that you have a bug in your app that plays poorly with a bug in Win32. A quick search for BufferedGraphicsContext.CreateCompatibleDIB yielded this question on SO (link to top answer) which indicates a resource leak may be at fault:
http://stackoverflow.com/questions/1209769/system-componentm...
I see nothing wrong with exceptions, I do have a problem with (1) checked exceptions, and (2) catching exceptions prematurely and (3) people not learning how to use "finally" so they do (2) and rethrow.
Languages like Go and Scala roll out various mechanisms that bring us back to the bad old days of C, when we had to check the return/value and or the error code after every function call... if we wanted error handling to work.
The trouble with this approach is that it increases code bulk. For CS class projects, this isn't so bad, but when you're building real systems, the complexity of the error handling can approach or exceed the complexity of the "normal" path and when that happens you're in deep trouble.
Exceptions drastically reduce code bulk by introducing default "abort" behavior, which can itself be aborted at any level of the program and which can invoke cleanup anywhere in between.
Many programmers in many situations would be perfectly happy to catch "failure to open a file" and "failure to open a database connection" and "failure to connect to a network host" with one simple handler that logs the failure and either aborts, retries or ignores.