Skip to content

[Proposal] try-catch expressions #132

Description

@ashmind

Problem

This is one of the issues when a small change to logic significantly changes code structure.
Let's say I have the following:

var x = Get();
Use(x);

Now I decide I want to handle Get() exceptions here (of course, separately from Use()).
My code becomes:

TypeOfX x;
try {
    x = Get();
}
catch (Exception ex) {
    throw new MuchBetterException("MuchBetterMessage", ex);
}
Use(x);

Now the x is separated from its definition, I can't use var, etc.

Potential solution

Provide an expression from of try, for example:

var x = try Get() catch (Exception ex) {
    throw new MuchBetterException("MuchBetterMessage", ex);
}
Use(x);

or maybe even

var x = Get() catch (Exception ex) {
    throw new MuchBetterException("MuchBetterMessage", ex);
}
Use(x);
Pros:
  1. Makes code structure clearer.
  2. Allows var.
Cons:
  1. What if exception handling isn't a single-line expression? {} syntax allows for it, but what if we wanted to return a value for x? return there would be super-confusing, but there is no other way in current C# to achieve something like that.

Other thoughts

If Cons are resolved somehow, I would love to see it for switch and other statements as well.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions