Skip to content

Automatic Handling of Unchecked Errors in Go #70794

@mole18

Description

@mole18

Proposal Details

Background

In Go, error handling is typically done through return values. While this explicit error handling improves code readability, it can sometimes be verbose and prone to missing error checks.

Motivation

The current error handling mechanism requires developers to explicitly check errors every time a function that may return an error is called. This can lead to verbose code and increases the risk of overlooking error checks. Introducing a mechanism to automatically handle unchecked errors can simplify the code and enhance safety.

Proposal

Implement a feature at compile-time or runtime to automatically detect and handle unchecked errors. When a function call returns an error and that error is not explicitly handled, the compiler or runtime will automatically return the error to the caller.

Example

Copy Code
func inner() error {
    // Some operations that might fail
    return fmt.Errorf("some error")
}

func outer() error {
    // Current approach:
    // err := inner()
    // if err != nil {
    //     return err
    // }

    // Proposed approach:
    _ = inner() // Automatically handled by returning the error if not nil
}

Impact

Advantages

Simplified Code: Reduces repetitive error-checking code.
Reduced Oversight: Automatically handles unchecked errors, lowering the risk of missing error checks.

Potential Drawbacks

Debugging Complexity: Automatic error handling might complicate debugging as the error propagation path is no longer explicit.
Deviation from Current Practice: This approach differs from Go's current philosophy of explicit error handling, requiring developers to adapt.

Alternatives

Use linting tools to flag unhandled errors during development.
Introduce new language features, such as a try keyword, to simplify error handling.

Conclusion

By automatically handling unchecked errors at compile-time or runtime, the error handling process in Go can be simplified, reducing the risk of missing error checks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    LanguageChangeSuggested changes to the Go languageProposalerror-handlingLanguage & library change proposals that are about error handling.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions