I am just learning Go programming language. I just read about the way of error handling in Go. There is a nice explanation but I have some confusion about it. The typical way of handing error in Go is just returning error as a second value of function:
f, err := Sqrt(-1)
if err != nil {
fmt.Println(err)
}
Very simple. But let say I am a library developer and I might want to know the client that my function can throw some error nad client must handle it.
In Java, I have throws
clause. So, client must have to put it in those try...catch
blocks
In Go, I can return error from a function; but let say if client of library avoid to handle it then how do I gracefully tell him to handle it?
Edit: I am just exploring a language. Not trying to mix java's thinking with Go and respect everyone's philosophy of doing it. I just asked because I wanted to know if there is any keyword because I haven't learnt Go very well yet.
Your library should also pass the err back through its exposed functions. You'll notice that many of the methods in the std library have a return value and an error so people should be used to having to handle errors.
If you really want to have behavior that appears similar to java you can use panic(), but note in golang panic should only be used for unrecoverable errors, or programmer errors (not runtime errors that can be recovered from)
Either way you can't force a client to handle it. It is their responsibility.
That's the philosophy of Go: If the developer sees that a function returns an error, it's then his responsibility to check the error. The programming language won't force you to do it.
Rob Pike's reasoning behind this is that errors are not special and therefore, there is no need for a specialized language construct (i.e. try/catch
) to handle them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With