Why does go not have exceptions




















If you get it wrong and it's easy to make this kind of mistake , then the caller ends up seeing your intermediate values. But they aren't a silver bullet. It will make sure you release resources on a throw, but doesn't free you from having to think about corruption of object state and callers seeing intermediate values. So, for a lot of people, it's easier to say, by fiat of coding style, no exceptions.

If you restrict the kind of code you write, it's harder to introduce these bugs. If you don't, it's fairly easy to make a mistake. Lots of experts have gotten it wrong.

If it's really that complex and has so many nuances, maybe that's a good sign that you need to ignore that feature. Exceptions are a similar story. A number of designs for exceptions have been proposed but each adds significant complexity to the language and run-time. By their very nature, exceptions span functions and perhaps even goroutines; they have wide-ranging implications.

There is also concern about the effect they would have on the libraries. They are, by definition, exceptional yet experience with other languages that support them show they have profound effect on library and interface specification. It would be nice to find a design that allows them to be truly exceptional without encouraging common errors to turn into special control flow that requires every programmer to compensate. In other words, they haven't yet figured out how to support exceptions in Go in a way that they think is satisfactory.

They are not saying that Exceptions are bad per se ;. We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code.

It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional.

Go takes a different approach. For plain error handling, Go's multi-value returns make it easy to report an error without overloading the return value.

A canonical error type, coupled with Go's other features, makes error handling pleasant but quite different from that in other languages. Go also has a couple of built-in functions to signal and recover from truly exceptional conditions. The recovery mechanism is executed only as part of a function's state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code.

So the short answer is that they can do it differently using multi-value return. And they do have a form of exception handling anyway. If you want to know why Linus thinks exceptions are crap, the best thing is to look for his writings on the topic. It's especially broken for kernels.

Exceptions are not bad per se, but if you know they are going to happen a lot, they can be expensive in terms of performance. The rule of thumb is that exceptions should flag exceptional conditions, and that you should not use them for control of program flow. I disagree with "only throw exceptions in an exceptional situation.

Exceptions are for error conditions execution failures. NET Libraries 2nd Edition. The chapter on exception throwing is without peer. Some quotes from the first edition the 2nd's at my work :. There are pages of notes on the benefits of exceptions API consistency, choice of location of error handling code, improved robustness, etc.

There's a section on performance that includes several patterns Tester-Doer, Try-Parse. Exceptions and exception handling are not bad. Like any other feature, they can be misused. From the perspective of golang, I guess not having exception handling keeps the compiling process simple and safe. So it makes sense to refuse exceptions. Exceptions make sense in code were it's okay to drop the current task on the floor, and where common case code has more importance than error handling.

But they require code generation from the compiler. For example, they are fine in most high-level, user-facing code, such as web and desktop application code. Exceptions in and of themselves are not "bad", it's the way that exceptions are sometimes handled that tends to be bad. There are several guidelines that can be applied when handling exceptions to help alleviate some of these issues.

Some of these include but are surely not limited to :. Typical arguments are that there's no way to tell what exceptions will come out of a particular piece of code depending on language and that they are too much like goto s, making it difficult to mentally trace execution. There is definitely no consensus on this issue. I would say that from the point of view of a hard-core C programmer like Linus, exceptions are definitely a bad idea. A typical Java programmer is in a vastly different situation, though.

Exceptions aren't bad. If you have a bunch of code already that's not exception safe, then they're bad in that context. If you're writing really low level software, like the linux OS, then they're bad. If you like littering your code with a bunch of error return checks, then they not helpful.

Say you are on a project and every controller around 20 different major ones extends a single superclass controller with an action method. Then every controller does a bunch of stuff different from each other calling objects B, C, D in one case and F, G, D in another case. Exceptions come to the rescue here in many cases where there was tons of return code and EVERY controller was handling it differently.

I whacked all that code, threw the proper exception from "D", caught it in the superclass controller action method and now all our controllers are consistent. Previously D was returning null for MULTIPLE different error cases that we want to tell the end-user about but couldn't and I didn't want to turn the StreamResponse into a nasty ErrorOrStreamResponse object mixing a data structure with errors in my opinion is a bad smell and I see lots of code return a "Stream" or other type of entity with error info embedded in it it should really be the function returns the success structure OR the error structure which I can do with exceptions vs.

Theoretically they are really bad. In perfect mathematical world you cannot get exception situations. Look at the functional languages, they have no side effects, so they virtually do not have source for unexceptional situations. But, reality is another story.

We always have situations that are "unexpected". This is why we need exceptions. I think we can think of exceptions as of syntax sugar for ExceptionSituationObserver. You just get notifications of exceptions. Nothing more. With Go, I think they will introduce something that will deal with "unexpected" situations. I can guess that they will try to make it sound less destructive as exceptions and more as application logic. But this is just my guess. One of the key design intentions of exception handling is to allow methods to ensure that they will either satisfy their post-conditions or throw an exception, and also ensure that any cleanup which needs to happen before a method can exit, will happen.

Even if exception handling would generally be good, it's not unreasonable to regard as unacceptable an exception-handling paradigm that fails to provide a good means for handling problems that occur when cleaning up after other problems. That isn't to say that a framework couldn't be designed with an exception-handling paradigm that could ensure sensible behavior even in multiple-failure scenarios, but none of the top languages or frameworks can as yet do so.

I havent read all of the other answers, so this ma yhave already been mentioned, but one criticism is that they cause programs to break in long chains, making it difficult to track down errors when debugging the code. For example, if Foo calls Bar which calls Wah which calls ToString then accidentily pushing the wrong data into ToString ends up looking like an error in Foo , an almost completely unrelated function.

For me the issue is very simple. Many programmers use exception handler inappropriately. More language resource is better.

Be capable to handle exceptions is good. One example of bad use is a value that must be integer not be verified, or another input that may divide and not be checked for division of zero The statement: "a professional code NEVER fails" might be illusory, if some of the issues processed by the algorithm are uncertain by its own nature.

Perhaps in the unknown situations by nature is good come into play the exception handler. I was recently reminded of this while going through the Go FAQ and being reminded that Go does not have exceptions. If you've always coded in a language that has exceptions, this ought to jump out at you. Go does not have try or catch.

Despite those language constructs existing for decades, Go chose to have Defer, Panic, and Recover instead. By convention and design, Go encodes an extremely strong opinion that errors should be returned, not thrown. Relying on exception handling to handle errors either leads to convoluted code or unhandled errors.

If you're thinking that you don't write this sort of code very often, you're probably not thinking through your failure modes enough. Aside - some authors like this Redditor and Matt Warren make a performance driven argument for encouraging developers to not overuse exceptions. Exceptions involve a memory and compute intensive stack search. This matters at scale, but most of us will never run into this so I choose not to make a big deal out of it.

You might notice the ironic inversion - it is errors that are "exceptional", while exceptions are routine. This was very confusing to your humble author. This is no doubt due to the fact that JavaScript , Python , and other languages treat errors and exceptions as synonyms. So we throw Error s when we really mean to throw exceptions. PHP and Java seem to have this difference baked into the language. To make things extra confusing, Go uses error where other languages would call exceptions, and relies on panic to "throw" what other languages would call errors.

The realization that we need different paradigms for handling errors and exceptions is of course not new. Do not allow this language in its present state to be used in applications where reliability is critical.

Note: Go seems to have a strong opinion that "Errors" are routine and Exceptions not formally named, but used in panic are Exceptional - in direct opposition to other languages. I have opted to use Go-native terminology - minimizing confusion locally at the cost of increasing global confusion. Errors are values in Go — made to be passed, not thrown. Go's FAQ is worth quoting here:. We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code.

It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional. When something goes wrong, your default choice should be using multi-value returns to report errors:. This pattern would be subject to the same weaknesses I outlined above, except for the fact that Go will refuse to compile if you 1 don't assign all returned values at the callsite or 2 don't use values that you assign. These two rules combined guide you to handle all errors explicitly near their origin.

Exceptions still have a place — but the language reminds you how rarely you should use it, by calling it panic. To work around this and gently nudge you, Node uses error-first callbacks :. This pattern is idiomatic in most Node libraries, but the further we get away from Node, the more we tend to forget that there is an alternative to throwing errors, when writing libraries and app code.

And we are right back where we started - being able to fling errors and exceptions arbitrarily high up and having to handle both in the same place. Thanks to Charlie You and Robin Cussol for reviewing drafts of this post. In JavaScript, Error s are just another type of object. So you can return new Error 'message' instead of throwing it, and TypeScript will modify the return type accordingly.

On the flipside, you can throw something that's not an Error if you really want. Though some linter configurations might complain at you if you do this.

Isn't this the other way around? I remember someone I forget who saying, "Exceptions should be reserved for exceptional circumstances.

Reserve exceptions for situations that shouldn't happen. I don't know if I'm all in on that. It's something I'm still mulling on. Just had to say it because it seems like you see it differently. Maybe it's just a nomenclature issue. Another thing is: I feel like we may be co-opting language terminology and constructs into our programming model, rather than the other way around.

Instead Go allows functions to return an error type in addition to a result via its support for multiple return values. By declaring a return value of the interface type error you indicate to the caller that this method could go wrong. In an internet connected world, where every input from a network must be considered hostile, is the failure to parse a string into a date really exceptional? Of course not.

In panic ing you never assume that your caller can solve the problem. Hence panic is only used in exceptional circumstances, ones where it is not possible for your code, or anyone integrating your code to continue. The decision to not include exceptions in Go is an example of its simplicity and orthogonality.

Using multiple return values and a simple convention, Go solves the problem of letting programmers know when things have gone wrong and reserves panic for the truly exceptional.

How does Go get exceptions right? Why, by not having them in the first place. First, a little history. Enter Go Go solves the exception problem by not having exceptions.



0コメント

  • 1000 / 1000