Skip to content

Inline catching #4205

Open
Open
@Protonull

Description

@Protonull

This is a request for Zig-style inline catching, which would allow something like the following:

final int example = int.parse("123") catch 0;

Which would then obviate the need for specific APIs like:

final int example = int.tryParse("123") ?? 0;

The problem is that not everything has a premade API that returns null if an error occurred. In fact, there may be some use cases, such as config parsing, where someone may wish to retain null as a valid return type distinct from there having been an error. And if you're someone who cares about finality (that once a variable is set, it cannot be changed), then your options are rather limited.

For example, the following is not possible:

final int example;
try {
    example = int.parse("123");
}
catch (_) {
	example = 0; // Error: The final variable 'example' can only be set once.
}
print("Example: $example");

The only way that I've found to do this is via:

final int example = ((){
    try {
        return int.parse("123");
    }
    catch (_) {
        return 0;
    }
})();
print("Example: $example");

Which is far from ideal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions