Skip to content

[Proposal] try-catch expressions #132

Closed

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

  1. omariom commented on Jan 29, 2015

    @omariom

    @ashmind, what do you think about this:

    var value1 = Catch(Get, 33);
    var value2 = Catch(()=> Get(123), ex => ex is TimeoutException ? 33 : 22);
    var value3 = Catch(Get, ex => { throw new Exception("MuchBetterMessage", ex);});
    
    Use(value1());
    
    public Func<T> Catch<T>(Func<T> value, T fallbackValue)
    {
        return Catch(value, ex => fallbackValue);
    }
    
    public Func<T> Catch<T>(Func<T> value, Func<Exception, T> exHandler)
    {
        return ()=>
        {
            try
            {           
                return value();
            }
            catch (Exception ex)
            {
                return exHandler(ex);
            }
        };
    }
  2. ashmind commented on Jan 29, 2015

    @ashmind
    ContributorAuthor

    @omariom I think it is a fair approach, but having this kind of thing on language level would make it available and consistent for everyone -- I don't really see many people using language-construct-libs at the moment. Also as it is this does not provide a way to rethrow the exception while preserving the stack (can be done, but makes it more complex).

  3. XuTpuK commented on Feb 28, 2015

    @XuTpuK

    I met similar problem and I think problem of this verbosity is "braces conception". Somewhere (like in "if {}" braces make REAL block, which wraps local piece of functionality. But in case of "try {}" these braces just mark portion of operators (in the same scope!) which should be "guarded". But language architectors doesn't bother with that and declare ANY braces as a "block". Probably something should be done to avoid this simplification and look at language constructs more deep.
    Anyway, this or other way we should make try{}catch things more simple.

  4. alrz commented on Feb 11, 2016

    @alrz
    Member

    👍

    This would prevent a huge try block or many nested ones and a level of indentation, instead you can write a specific catch for each function, e.g.

    var a = F() catch {
     ..
    }
    
    var b = G() catch {
     ..
    }
    

    Perhaps endpoint of the embedded-statement after catch should not be reachable like else in let (#6400)? I wonder how this would work with the let .. when .. else statement.

    Also, catch can't return a value here,

    T result;
    try {
      result = F();
    } catch {
      result = G();
    }

    Doesn't this propose any way to make this easier?

  5. HaloFour commented on Feb 11, 2016

    @HaloFour

    Would this be limited strictly to a single catch block? Otherwise I'm not sure you'd avoid the ambiguity in associating each catch block to its correct try block if this expression were to be within a nested try statement.

  6. MadsTorgersen commented on Aug 15, 2016

    @MadsTorgersen
    Contributor

    The main problem with an example along the lines of var x = try expr catch (...) { ... } or (syntactical variations thereof) is that x wouldn't be definitely assigned after the expression, unless you require the catch block itself throws, or you give it some way to affect the outcome of the try expression.

    Should a new proposal address those issues, we'd still need to consider whether this is worthwhile to spend language surface area on. I currently think it is not.

  7. added a commit that references this issue on Sep 4, 2026
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