Skip to content

proposal: Go 2: simplify error handling with try err == nil {} except {} #33387

@gwax

Description

@gwax

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")
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions