by hot_gril · 2y ago · 0 comments
Go _doesn't_ have any form of checked exceptions, though, which are required by the compiler to be caught by the caller.
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.
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 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.