Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Go's equivalent to 'throws' clause?

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.

like image 657
Krupal Shah Avatar asked Dec 05 '22 17:12

Krupal Shah


2 Answers

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.

like image 148
Josh Wilson Avatar answered Dec 09 '22 15:12

Josh Wilson


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.

like image 40
W.K.S Avatar answered Dec 09 '22 13:12

W.K.S