Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/catch oneliner available?

Just as you can convert the following:

var t; if(foo == "bar") {     t = "a"; } else {     t = "b"; } 

into:

t = foo == "bar" ? "a" : "b"; 

, I was wondering if there is a shorthand / oneline way to convert this:

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

Is there a method of doing this in a shorthand way, preferably an oneliner? I could, of course, just remove the newlines, but I rather mean something like the ? : thing for if.

Thanks.

like image 362
pimvdb Avatar asked Feb 26 '11 11:02

pimvdb


People also ask

Can we use continue in try catch?

As you are saying that you are using try catch within a for each scope and you wants to continue your loop even any exception will occur. So if you are still using the try catch within the loop scope it will always run that even exception will occur.

What is try catch block with example?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Can we have try in catch?

Java For TestersYes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.


2 Answers

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; }  
like image 159
rene Avatar answered Sep 30 '22 10:09

rene


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.

like image 36
In silico Avatar answered Sep 30 '22 08:09

In silico