Try/catch oneliner available?

You could use the following function and then use that to oneline your try/catch. It's use would be limited and makes the code harder to maintain so i'll never use it.

var v = tc(MyTryFunc, MyCatchFunc);

tc(function() { alert('try'); }, function(e) { alert('catch'); });


/// try/catch 
function tc(tryFunc, catchFunc) {
     var val;
     try {
        val = tryFunc();
     }
     catch (e) {
         val = catchFunc(e);
     }
     return val;
} 

No, there isn't a "one-liner" version of try-catch besides simply removing all the newlines.

Why would you want to? Vertical space doesn't cost you anything.

And even if you'll settle for removing all the newlines, this, in my opinion, is harder to read:

try{t = someFunc();}catch(e){t = somethingElse;}

than this:

try {
    t = someFunc();
} catch(e) {
    t = somethingElse;
}

What you have is perfectly fine. Readable code should be a priority. Even if it means more typing.


There is one liner available as npm package try-catch. You can use it this way:

const tryCatch = require('try-catch');
const {parse} = JSON;

const [error, result] = tryCatch(parse, 'hello');

There is similar approach for async-await try-to-catch:

const {readFile} = require('fs').promises;

read('./package.json').then(console.log);

async function read(path) {
    const [error, data] = await tryToCatch(readFile, path, 'utf8');

    return data || error.message;
}

All this wrappers do is wrap one function with try-catch block and uses destructuring to get result.

Also there is an idea to use something similar to Go style error handling:

// this is not real syntax
const [error, result] = try parse('hello');

You can get it down to two lines.

try { doSomething(); }
catch (e) { handleError(); }

Or, in your specific example, 3 lines.

var t;
try { t = doSomething(); }
catch (e) { t = doSomethingElse(); }

Either way, if your code allows for it, a two liner is much more concise, IMO, than the typical try/catch block.