-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Closed
Labels
FrozenDueToAgeLanguageChangeSuggested changes to the Go languageSuggested changes to the Go languageProposalProposal-FinalCommentPerioderror-handlingLanguage & library change proposals that are about error handling.Language & library change proposals that are about error handling.v2An incompatible library changeAn incompatible library change
Milestone
Description
Premised on the expectation that people frequently want to execute a series of statements and check for errors after each statement but frequently want to respond to any error in the same way, we can construct a special statement block to execute these repeated checks for us.
Try statements
"Try" statements specify conditional transfer of control to an "except" clause based on repeated checks of a boolean expression within a block. If the expression evaluates to false after any statement within the block, execution is immediately passed to the "except" branch.
TryStmt = "try" Expression Block "except" Block .
Example:
var err error
var people People
try err == nil {
jsonFile, err := os.Open("people.json")
jsonBytes, err := ioutil.ReadAll(jsonFile)
err = json.Unmarshal(jsonBytes, &people)
} except {
return nil, errors.Wrap(err, "failed to read people.json")
}
The above translates directly to:
var err error
var people People
{
{
jsonFile, err := os.Open("people.json")
if !(err == nil) {
goto Except
}
jsonBytes, err := ioutil.ReadAll(jsonFile)
if !(err == nil) {
goto Except
}
err = json.Unmarshal(jsonBytes, &people)
if !(err == nil) {
goto Except
}
goto NoExcept
}
Except:
{
return nil, errors.Wrap(err, "failed to read people.json")
}
NoExcept:
}
And can be used to replace:
jsonFile, err := os.Open("people.json")
if err != nil {
return nil, errors.Wrap(err, "failed to read people.json")
}
jsonBytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
return nil, errors.Wrap(err, "failed to read people.json")
}
var people People
err = json.Unmarshal(jsonBytes, &people)
if err != nil {
return nil, errors.Wrap(err, "failed to read people.json")
}
boreq, sirkon, arl, sagarkrkv, mattn and 22 more
Metadata
Metadata
Assignees
Labels
FrozenDueToAgeLanguageChangeSuggested changes to the Go languageSuggested changes to the Go languageProposalProposal-FinalCommentPerioderror-handlingLanguage & library change proposals that are about error handling.Language & library change proposals that are about error handling.v2An incompatible library changeAn incompatible library change