5 ms·
The biggest expressivity pain point in practice for me is try/catch not being an expression, so I can’t do const c = try { … }
by baq 3y ago
The biggest expressivity pain point in practice for me is try/catch not being an expression, so I can’t do
const c = try { … }
- lovasoa 3y agoWith async code, there is const c = myAsyncFun() .catch(e => …)
- WorldMaker 3y agoThat leaves c as Promise which was not the type they were looking for. You'd still have to unwrap the promise and deal with the result or rejection. The easiest way to do that is to use await, and if you are using await you'd be better off using try {} catch {} around the async function than .catch().
- jve 3y agoYes! 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.
- thdespou 3y agoZig can though: const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("Hello, {s}!\n", .{"world"}); }
- zkldi 3y agothat's not using `try` as an expression. can you do `let foo = try <code> (plus some handling for diverging in the other case?)`
- kaba0 3y agoIt can and you in fact either have to mark that you return that error when you use try, or you have to provide a default value in a catch block: fn potentiallyErrorReturningFunc() !u64 { ... } const foo = potentiallyErrorReturningFunc() catch { 0 }; One notable difference to most other languages is it being a value only, basically a product type of return value XOR error. These error values get serialized into a number by the compiler that is unique, and on the type system level you deal with sets of these error values. Quite clever in case of a low-level system, in my opinion.
- flohofwoe 3y ago> const foo = potentiallyErrorReturningFunc() catch { 0 }; Nitpick, but AFAIK this won't work and needs to be rewritten either to: const foo = potentiallyErrorReturningFunc() catch 0; ...or to: const foo = potentiallyErrorReturningFunc() catch blk: { break :blk 0; } (I wish there would be a more convenient way to return a value from a scope block, not necessarily with a "dangling expression" like Rust, but maybe at least getting rid of the label somehow)
- flohofwoe 3y agoYes, 'try' can be used like an expression in Zig which resolves to the unwrapped success-result of an error-union, or in case of an error immediately passes the error-result up to the calling function.
- xscott 3y agoWhat does a try expression like this do? Returns null/undefined on a throw? I suspect you could do something like: const c = attempt(() => ... ); where attempt invokes the lambda, catches any exceptions, and does what you want
- lmm 3y ago> What does a try expression like this do? Returns null/undefined on a throw? If an exception is caught, the expression evaluates to what the catch block evaluates to. (Similar to having if/else be an expression). Of course if the exception isn't caught then it propagates so the expression doesn't take a value.
- afandian 3y agoKotlin has this feature (`try` and `if` are expressions not statements), and a good model for return values. https://kotlinlang.org/docs/exceptions.html#exception-classes https://kotlinlang.org/docs/exceptions.html#exception-classe...
- not_alexb 3y agoI use iife for stuff like this. const c = ( ()=> { try: {...} } )()
- smcl 3y agoWould you not just move that `try { ... }` block into a separate function or method?
- austin-cheney 3y agoI never ever use try/catch in my code. The only time its really necessary is to wrap JSON.parse on use of untrusted input. For everything else it just feels sloppy as through there is insufficient logic in place for handling primary conditions versus edge cases. Also, try/catch will never compile in the JIT.
- macguillicuddy 3y agoPerhaps the place I use it most is that try/catch is how you deal with rejected promises that you've `await`ed in an `async` function.
- raxxorraxor 3y agoFor everything with the slightest bit of I/O it is quite practical if you have even the most trivial assumptions about its form. Sure, you can check for everything. It often is more effective, but not prettier or easier to read and of course you also will miss cases.
- austin-cheney 3y agoThis sounds like some hyperbolic framework nonsense. First of all I/O just means access to an API. I am going to presume you mean messages from a network. In that case a message from a network either sends or fails and in the case of sending try/catch does nothing for you but provide an error object, and you don't need try/catch to capture the error. In the case of receiving a network message the message comes in or it doesn't. If the message does come in and is malformed your application should be mature enough to handle that appropriately to the benefit of the user instead of crapping out some error messaging to the console. You don't need try/catch to do any of this. A simple if condition is more than sufficient. > check for everything You should check for everything. You only need to check for one thing and if you check for it you are already at 100% of everything. Did you get what you expected: Yes/No?
- thrashh 3y agoDisagree. Usually you don't need to just know if there is an error or not -- sometimes you need to know what that error is. For example, an I/O error versus your image-is-too-small error -- you need to respond to the user differently. I've seen plenty of web apps that treat I/O errors and user input errors as a generic "an error happened" and that is completely wrong. Proper exception bubbling means none of that code that encounters the errors needs to necessarily know how to handle the error and your app always responds correctly. That said, I don't use exceptions as much in JS because exception handling in JS is still very nascent. There's no base library of exceptions and telling different exceptions apart is not built-in to the language. In a language with more mature exception handling, it's a breeze.