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?
In current Go with the handle construct would look something like this:
handleerr{ifnotExist,ok:=err.(*os.ErrNotExist);ok{// Do stuff with notExist}elseifotherErr,ok:=err.(*pack.OtherErr);ok{// Do stuff with otherErr}}// Or if your list is very longhandleerr{switcherr.(type){case*os.ErrNotExist:// Code...case...:// ...default:// ...}}
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:
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.