Question

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++
}
Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top