The parent is really complaining about idiomatic Go. Which is fair, because idiomatic Go feels like writing Java 6 (that is to say, making lots of compromises due to limitations of the language).
The parent is really complaining about idiomatic Go. Which is fair, because idiomatic Go feels like writing Java 6 (that is to say, making lots of compromises due to limitations of the language).
No. An exception is a datatype. Not completely unlike an error type in concept, but intended for erroneous conditions that could have theoretically been caught at compile time (i.e. the programmer screwed up), as opposed to conditions that are not decidable at compile time (i.e. something happened in the outside world).
In Go, panic creates an exception, which may be the source of your confusion. The exception contains any metadata you passed to panic along with other data, like a stack trace. This is not panic in and of itself, though.
> but when writing idiomatic Go one would prefer error types over using panic
Not really. Idiomatic Go says that errors are in no way special and is faulty to think of them as being special. They are just values like any other. Go exceptions allow attaching any value as metadata.
The official line is that panic stack traversal should not cross package boundaries, but internal use is perfectly acceptable. Even the Go standard library does it.
Why is it that Go attract so many "experts" who have clearly never used the language even just once?
You might impose it upon yourself when you start to understand the pitfalls of using exceptional handlers for anything other than exceptions, but such is engineering. Everything comes with tradeoffs.
Within a package it can work, but then you'll find language support lacking. For example defer is scoped to a function so you need to write pretty unusual code to make the equivalent of a try block.
Go _doesn't_ have any form of checked exceptions, though, which are required by the compiler to be caught by the caller.
Of course, Go code uses panics much more sparingly than Java or C# or JS or Python use exceptions.
func outer() {
defer catch() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
// ...
doSomething() // Can panic
doSomethingElse() // Can also panic
}
vs JS: const outer = () => {
try { doSomething() } catch(err) { console.log(err) }
try { doSomethingElse() } catch(err) {
console.error("dang it bobby", err)
throw err
}
}
But in any real Golang situation, you'll be working with libraries or teammates who return (type, error) instead of using panics. You might say this isn't inherent to the language, but it kinda is when all the built-in standard libraries like net/http work this way and the official language style guide tells you to do this. func outer() {
r, err := doSomething()
if err != nil {
fmt.Println("Recovered:", r)
}
r, err := doSomethingElse()
if err != nil {
fmt.Println("Recovered else:", r)
}
}Why not?
func outer() {
func() {
defer catch() {
if r := recover(); r != nil {
fmt.Println("Recovered from doSomething:", r)
}
}()
doSomething() // Can panic
}()
func() {
defer catch() {
if r := recover(); r != nil {
fmt.Println("Recovered from doSomethingElse:", r)
}
}()
doSomethingElse() // Can also panic
}()
}
I don't get why we keep getting these "expert" comments from people who have never used Go before.Hell, if you long for try/catch for some reason, you can even get creative:
func try(fn func(), catch func(any)) {
defer func() {
if r := recover(); r != nil {
catch(r)
}
}()
fn()
}
func outer() {
try(func() {
doSomething()
}, func(r any) {
fmt.Println(r)
})
try(func() {
doSomethingElse()
}, func(r any) {
fmt.Println(r)
})
}
But then you soon start to realize how awful try/catch actually is, so...The recover is still function-wide in your example, which is what I said. You can nest funcs just to deal with this, but it's ugly, and code reviewers won't like it. I use Go on my team, and yeah I'm not as expert as the team who created Go here, but idk why you keep saying I've never used it. My complaint about "if err" is pretty common among Go users, who would understand the joke of calling it "Errlang."
Yes, it suffers all the same problems. And then doesn't even help you with the errors once you get them! You then have to resort to this kind of craziness to do something with the error:
try {
doSomething()
} catch(error) {
if (error instanceof FooError) {
console.log('foo')
} else if (error instanceof BarError) {
console.log('bar')
} else if (error instanceof BazError) {
console.log('baz')
} else {
console.log('unknown')
}
}
Which leaves you wondering why you didn't just write: err := doSomething()
switch {
case errors.Is(err, ErrFoo):
fmt.Println("foo")
case errors.Is(err, ErrBar):
fmt.Println("bar")
case errors.Is(err, ErrBaz):
fmt.Println("baz")
default:
fmt.Println("unknown")
}
At least Java gives you multiple catch blocks to make things slightly more sane.But I get the impression that those who find benefit in passing errors using exception handlers don't handle errors. If you don't have to worry about errors in the code you write, then I think there is a good case to be made that errors as exceptions is a better approach.
That is, after all, the difference between scripts and systems. Scripts can simply fail, leaving the user to try again. Errors as exceptions, or something in the same vein, make sense as the predominant mechanism in scripting languages. Systems, on the other, have to deal with failure. You don't get to just bubble it up and let the user deal with it. This is where errors as exceptions becomes a nightmare. Go is unabashedly a systems language. It is not meant to be a scripting language.
Different tools for different jobs.
They aren't different jobs, though. The two most common uses of JS are backend systems (like you'd often use Golang for) and web frontends, not scripts. Backends will usually catch errors in one place, an HTTP or similar handler, sending back the appropriate status code with maybe a payload. Golang backends do something similar, which is why you see so much "if err != nil... return err" in practice.
Python is more for scripts aka CLIs, but Python backends are fairly common too. And Golang CLIs are also common.
But at least we have a rule checking that you actually did something with the return statuses.
If you want to use a Result/Optional type I think that is way better than exceptions. As long as the compiler can enforce that you are acknowledging (or explicitly ignoring) both the happy and error cases. Ideally the error case for the Result/Optional type would also have an attached stack trace.
So, if I'm understanding you correctly:
An exception is an unexpected failure at runtime that could have been caught by the programmer. For example, you might have a switch block with a default block saying "this can never happen". The programmer might miss a case in the switch block leading to an exception. This would be analogous to an unchecked exception (RuntimeException) in Java -- these exceptions are not required to be caught.
In Go, `panic` creates an instance of the type `exception`. When `panic` is executed it attaches metadata like the stack trace to the created exception. When I say "exception" this is the behavior that most people think about.
An error is for an expected failure, like a file potentially not existing when performing I/O operations. Like you said (and this matches my understanding), error types are just a normal type -- really any type that implements the `Error` interface. There are a lot of utilities functions/libraries that act on that `Error` interface, like assertions for unit tests, the multierr library, etc.
`Error` is similar to a checked exception (Exception) in Java, though it misses the behavior you expect like requiring it to be caught, and the try-catch syntax. Additionally, you don't have the stack trace/metadata automatically added.
Go programmers seem to _heavily_ prefer errors over exceptions, even when they should be using `panic`.
My problem with errors in Go are that they are too easy to ignore accidentally and they don't contain stack traces, so they can be hard to track down. I inherited a codebase where we had _hundreds_ of unchecked errors being silently ignored.
I understand that these problems go away if you have linters or a very detail-oriented team, but I unfortunately have no power over the actions of my team before I join. It's also _very_ hard to convince a team that they've been doing things incorrectly by ignoring errors.
This is a problem for values of all types, not just errors. One I'm not sure we've figured out how to solve[1]. There are a few languages out there that force variable assignment to try and address the problem, but even then there is really nothing to say that you haven't accidentally ignored the variable assigned.
> It's also _very_ hard to convince a team that they've been doing things incorrectly by ignoring errors.
To be fair, if you are able to completely leave out entire blocks of logic without anyone noticing even under the most cursory of testing, perhaps it wasn't actually needed? Forgetting entire code branches isn't exactly a subtle bug.
[1] Short of going all the way to formal proofs.
But even assuming it is done sometimes, is the developer going to actually handle it? I don't know how many times I've come across "catch" blocks that are empty or something equally inappropriate. Nothing was gained. It turns out that programmers will still forget no matter how hard you try to hold their hand.
I'm not sure there is any other solution than to test it, and once you get into testing, entire blocks of logic missing are going to stick out like a sore thumb. Forgetting an entire branch is not exactly a subtle bug. At that point it really doesn't matter what language constructs you do or don't have available.
You are right, but the difference is that the programmer is making the choice to ignore that error versus accidentally ignoring the error.
And fair enough. It would be just as easy to forget to do that as it would be to forget to handle errors in any other language. There is no silver bullet here.
The difference is that the happy case is well-tested. If you aren't handled the error-free route you probably will notice that very quickly unless you aren't testing your code, even manually.
e.g. it doesn't matter if you ignore normal variable assignments because the programmer will usually catch that themselves. They will not likely catch all of the possible error assignments without some help.
> To be fair, if you are able to completely leave out entire blocks of logic without anyone noticing even under the most cursory of testing, perhaps it wasn't actually needed? Forgetting entire code branches isn't exactly a subtle bug.
In this case we were silently ignoring errors which caused multiple types of issues that we had to then manually track down. This is an entire class of defects that can be avoided with better tooling, either at the language level with checked exceptions, or with a linter like errcheck.