1

I need to be able to run a bunch of code if a statement is successful. If javascript had a try/catch/else then I would put all the code in the else and be done with it. I don't want to use a Boolean to mimic the else in try/catch/else. My understanding is that try can handle an error but can't IF do the same? If so, I'll have to use the IF but I don't want my program to crash if the QueryInterface fails. So my question is, if the QueryInterface fails, then the else will be executed in the IF below correct? If so then I guess the only reason to use a try/catch is to snag the error condition.

existing method:

try {
 channel = subject.QueryInterface(Ci.nsIHttpChannel);
} catch(err) {
 booSuccess = false;
 intErrorCount++
}
if (booSuccess == true) {
 ...bunch of stuff...
}

proposed method:

if (channel = subject.QueryInterface(Ci.nsIHttpChannel)) {
 ...bunch of stuff...
} else {
 intErrorCount++
}
Xi Vix
  • 1,381
  • 6
  • 24
  • 43
  • 3
    `booSuccess == true` - Ouch. – Bergi May 09 '14 at 01:45
  • Possible duplicate of [Javascript: What's more efficient, IF block or TRY/CATCH?](http://stackoverflow.com/questions/558914/javascript-whats-more-efficient-if-block-or-try-catch) – Kaspar Lee Mar 15 '16 at 13:08

2 Answers2

2

No, throwing an exception (which you catch with the first snippet) is very different from returning an error code (channel == 0, which the second snippet checks). They do not do the same.

What you might do to avoid that boolean variable is

try {
 channel = subject.QueryInterface(Ci.nsIHttpChannel);
 ...bunch of stuff...
} catch(err) {
 intErrorCount++
}

but that would also raise the error count if an exception happens in the bunch of stuff.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • unfortunately, there is a ton of code in the bunch of stuff ... to include nested trys ... I'm not sure how a try works inside another try. – Xi Vix May 09 '14 at 05:02
  • `try` works well inside `try`. The inner `try` will catch the exception, and if it can handle it execution goes on as normal. Or it cannot and wants to rethrow, or the handler code throws; then the outher `try` catches that exception. – Bergi May 09 '14 at 05:10
0

No you can't simply replace the try/catch with an if/else. If a line throws an error, the javascript interpreter will stop execution of that script.

sahbeewah
  • 2,690
  • 1
  • 12
  • 18