4 ms·
Yes! This just drives me crazy: string something = null; try { something = mayThrow(); } catch (SomeException ex) { log.Info(ex); } cat
by jve 3y ago
Yes! This just drives me crazy:
string something = null;
try {
something = mayThrow();
} catch (SomeException ex) {
log.Info(ex);
} catch (Exception ex) {
log.Fatal(ex);
throw;
}
if (something != null) {
...
}
Would be actually nice if it had F#'s try...with https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/exception-handling/the-try-with-expression https://learn.microsoft.com/en-us/dotnet/fsharp/language-ref... and would allow us something like:
var something = try {
mayThrow()
} with (SomeException ex) {
log.Info(ex);
} with (Exception ex) {
log.Fatal(ex);
throw;
}
Or some way to do pattern matching on exceptions for switch expression.
var something = mayThrow() switch {
(SomeException ex) => {
log.Info(ex);
return null;
}
(Exception ex) => {
log.Fatal(ex);
throw;
}
var passThru => passThru
}
- scotty79 3y agovar something = (() => { try { return mayThrow() } catch(SomeException ex) { log.Info(ex); return null; } catch(Exception ex) { log.Fatal(ex); throw; } })(); Close enough?
- baq 3y agonot really; can't immediately return from the lambda caller without throwing, always have to either try/catch anyway or if/else the return value of the lambda. (also, it's rather ugly to read and inconvenient to write.)
- jve 3y agoAnother idea, introduce ??? that would invoke on exception :) var something = (mayThrow() ??? (SomeException ex) => { log.Info(ex); return null} ) ??? (Exception ex) => { log.Fatal(ex); throw; }; Or maybe just start using Results as return type and get ValueOrDefault :) But when it comes to handling exceptions, I think it explodes there with ifs and processing IENumerables: https://github.com/altmann/FluentResults https://github.com/altmann/FluentResults But then again, simpler Results wrapper may be used perhaps. But it is a different way of coding and takes some mental shift on how to think about errors and distinguish between error results and true exceptions. Oh, csharplang already had discussion on the matters about try/catch single statements: https://github.com/dotnet/csharplang/issues/786 https://github.com/dotnet/csharplang/issues/786
- scotty79 3y ago> can't immediately return from the lambda caller without throwing You want to immediately return in the middle of something that was supposed to simulate just evaluating an expression? You can't immediately return in the middle of 2+2 as well because return is a statement and can't be a part of expression.