3 ms·
Doesn't look that much cleaner than try/catch, to be honest. What I would really like to see in C#: public int DoThing(int y) { //logic } catch
by gambler 8y ago
Doesn't look that much cleaner than try/catch, to be honest.
What I would really like to see in C#:
public int DoThing(int y)
{
//logic
}
catch (SomeException e)
{
//handle things
return 0;
}
This would remove a lot of useless syntactic garbage without the need for any radical changes in the language. (It would translate to try-catch that wraps the entire body of the method.)
But so far I gave up on syntax-level error handling of any complexity. Generally, I just write multiple "agents" and all the error handling, retries and recovery is simply done by separate agent(s). The agent that tries to perform the initial actions simply records that it failed in some persistent storage and terminates or goes on to do something else.
- ilitirit 8y ago> It would translate to try-catch that wraps the entire body of the method It would not not be the same unless you change how scoping works in these instances, and that can introduce other complexities, e.g. how to limit scope so that some things are inaccessible to the catch block.
- gambler 8y agoThis: public void DoThing(){ //code } catch (Exception x){ } finally { } would simply be syntactic sugar for this: public void DoThing(){ try { //code } catch (Exception x){ } finally { } } It's consistent.
- ilitirit 8y agoYes, and that only works by changing how scoping works. Unless of course you don't care about the variables created inside. i.e. public void DoThing() { var someVar = SomeStaticClass.FooFunc(); someVar.DoSomething(); } catch (Exception x) { // Scoping rules will need to change // to put someVar in scope: _logger.Log($"{someVar.GetId()} is invalid"); } finally { someVar.Cleanup(); } And this also implies that there's no way to make a variable declared inside the method inaccessible to the catch block without additional changes to the language.
- gambler 8y ago>Unless of course you don't care about the variables created inside. In majority of cases I really don't care about the variables created inside. If I can't handle an error just by looking at the exception and method arguments I usually refactor. In my view, error handling should not be intertwined with the "happy path". It makes reasoning about non-trivial code much harder. For other cases the old syntax will still be available. And yes, the value of "finally" in such a shorthand is dubious. I just added it to make it clear how the rewrite rule would work.