Try Expressions

I think it could be useful if we could try an expression, and if it throws return undefined.


let x = (try JSON.parse(y)) ?? {};

equivalent to:

let x;
try{ x = JSON.parse(y) } catch { x = {}};

1 Like

If an exception is deemed to be regularly ignored to the point that a dedicated syntax is wanted, it is questionable that it should be thrown in the first place. Although you are not necessarily able to correct a badly designed API, you are free to wrap it. Personally, I use:

JSON.$parse = function (...args) { 
    try {
        return JSON.parse(...args);
    catch (e) { }
function try$(closure) {
     try { closure() } catch (e) { }

try$(() => JSON.parse())

Do you use the above pattern enough to warrant syntactic sugar for it?

This is more or less a duplicate of Try-catch oneliner

1 Like