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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With