Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appropriate inline try catch

In Javascript (or for the most part, ECMAscript in general), which is the most appropriate way to write this?

try { ajax.abort() } catch(e) { console.error (e) }

or

try { ajax.abort(); } catch(e) { console.error (e); }

It seems like semi-colons are unneeded for this situation but at the same time I normally write this on 5 lines instead of one in which case I used semicolons for their standard programmatic purpose (eol).

Both work, and I'm sure both will validate, so which is semantically correct?

like image 742
Jacksonkr Avatar asked Feb 08 '26 04:02

Jacksonkr


1 Answers

Here's an inline try-catch for expressions. You can compute a value in one go, but still catch exceptions and fall back to a default value when evaluation fails - similar in spirit to the ternary ?: operator:

function trycatch(func, fail) {
    try { return func() }
    catch(e) { return fail }
}

The expression must be wrapped up in a function, so it gets executed inside trycatch() not outside of it. Example use:

let value = trycatch(() => JSON.parse("parsing fails on this input"), null)
like image 192
Marcin Wojnarski Avatar answered Feb 12 '26 04:02

Marcin Wojnarski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!