re: Go 2 Draft: Error Handling VIEW POST


Thanks for your elaborate reply.

Maybe I shouldn’t do this, but in my head I compare this to the try/catch/finally concept. Catch comes after try but cannot use any variables that have not been declared before try. But it makes the flow much clearer since you usually read code from top to bottom.
And one of my questions was how to implement multiple catch blocks. With try/catch i can have muktiple of those constructs or even multiple catch blocks. Let’s say I have file operation and a parsing operation and I want to handle them differently, I could declare two different catch blocks. How would I do this with check/handle?

It would look something like this:

In current Go with the handle construct would look something like this:

handle err {

    if notExist, ok := err.(*os.ErrNotExist); ok {
        // Do stuff with notExist
    } else if otherErr, ok := err.(*pack.OtherErr); ok {
        // Do stuff with otherErr

// Or if your list is very long
handle err {
    switch err.(type) {
    case *os.ErrNotExist:
        // Code...
    case ...:
        // ...
        // ...

Note that the notExist, ok := err.(*os.ErrNotExist) is how you typecast in Go. Also, a semicolon in an if statement means "just execute the left side normally and evaluate the right side as the condition", although any variables declared on the left side have block scope within the if statement.

Errors in Go are just an interface, so you just cast them to the error that you want to check.

code of conduct - report abuse