[ACCEPTED]-Javascript: What's more efficient, IF block or TRY/CATCH?-try-catch

Accepted answer
Score: 21

Exceptions should be used for exceptional 6 circumstances (i.e. things that you don't 5 expect to happen normally). You should 4 not, in general, use exceptions to catch 3 something that you can test for with an 2 if statement.

Also, from what I understand, exceptions 1 are much more expensive than if statements.

Score: 18

Use the if statement. I don't know what 17 the overhead is for a TRY/CATCH, but I suspect 16 it's far greater than evaluating a boolean 15 expression. To hit the TRY/CATCH you will 14 have to: execute a statement, generate 13 an error [with that associated overhead], log 12 the error (presumably), made a stacktrace(presumably), and 11 moved back into the code. Additionally, if 10 you have to debug code near those lines 9 the real error could get obfuscated with 8 what you are TRY/CATCHing.

Furthermore, it's 7 a misuse of TRY/CATCH and can make your 6 code that much harder to read. Suppose 5 you do this for longer or more obfuscated 4 cases? Where might your catch end up?

This 3 is referred to as Exception handling

EDIT: As commented below, you 2 only take the runtime performance hit if 1 you actually cause an exception.

Score: 12

The other answers are correct, try/catch is for exceptional 24 circumstances and error handling. if conditions 23 are for program logic. "Which is faster?" is 22 the wrong question.

A good rule of thumb, if 21 you're doing nothing with the exception, it's 20 probably not an exception!

To figure out 19 which to use, let's break down your if condition.

  1. typeof jQuery == 'function' Is the jQuery() function defined?
  2. typeof nav == 'object' Does the nav global variable contain an object?
  3. typeof pageid != 'undefined' Is the pageid global variable defined?
  4. typeof document.getElementById('leftnav') == 'object' Does the document contain a leftnav element?

The 18 first is clearly an exception. You ain't 17 getting far without a jQuery() function.

The 16 second is also an exception. You're not 15 going anywhere without a nav object.

The 14 third is an exception. You need a pageid 13 to do anything.

The fourth is probably logic. "Only 12 run this code if there is a leftnav element". It's 11 hard to tell because the rest of the code 10 doesn't reference a leftnav element! Only 9 the comments do, a red flag. So it's probably 8 a programming mistake.

So I'd probably do 7 this (with apologies if I'm butchering jQuery):

var intvar = setInterval(function() {
    // If there's no leftnav element, don't do anything.
    if( typeof document.getElementById('leftnav') != 'object') {

    try {

        //set display classes for nav
            .addClass('subselect');     //topnav
            .addClass('subselect');     //leftnav
    catch(err) {
        ...do something with the error...

...but 6 I'd really examine if the leftnav element 5 check is applicable.

Finally, I can't help 4 but comment that this "function" is working 3 with global variables. You should instead 2 be passing nav and pageid into the function in order 1 to maintain encapsulation and your sanity.

Score: 3

I would write the following code:

var startTime = (new Date()).getTime();
for (var i=0; i < 1000; ++i) intvar();
var endTime = (new Date()).getTime();
alert("Took " + ((endTime - startTime) / 1000.0) " seconds");

Then I 10 would try both versions of intvar and see 9 which runs more quickly. I'd do this myself 8 but I don't have the page layout you do 7 so my code wouldn't work.

Some stylistic 6 comments - it doesn't seem necessary to 5 test that jQuery is a function. If it isn't, your 4 webpage is likely messed up such that not 3 running the intvar code will not help you. If 2 you rarely expect the exceptions to be thrown, I'd 1 use the try/catch.

Score: 2

For the provided example where you are wrapping 20 a try/catch around a block of code that 19 should always run anyway (unless if something 18 horrible happens), it is good form to use 17 try/catch. An analogy for you: do you always 16 test "Is the sky Blue?" in your if statement, or 15 would you wrap it in a try/catch that is 14 triggered only when the sky happens to turn 13 Green.

Use the If statement method if you 12 are dealing with user provided input or 11 if the chances of a function not existing 10 is much higher due to something else happening 9 in the code.

Keep in mind that if you don't 8 trigger the exception you don't have any 7 unwinding or backtracking across code. In 6 the example the catch will only execute 5 if something is wrong (jQuery is missing 4 or some such thing), however the if statement 3 method has an evaluation happening on EVERY 2 SINGLE CALL to that function - you shouldn't 1 do more work than you have to.

Score: 0

To directly answer the question, as everyone 16 else has, the try..catch is likely going 15 to be more expensive if there actually is 14 an error.

To point out some additional errors 13 in the code beyond what others have already 12 pointed out:

These two codes are not at all 11 equivalent. To explain, even though the 10 codes appear to do the exact same thing, they 9 do not.

In the case of the if() check, NONE 8 of the code is executed. In the case of 7 the exception handler, each line of code 6 inside the exception handler will be executed. SO, what 5 happens if the error occurs in the second, or 4 the third line? Then you've got something 3 completely different happening in your code 2 than what you get if you check the conditions 1 before executing any of it.

Score: 0

Aside from the answers given, I want to 46 add some thoughts on this subject.

Exceptions 45 that are unforeseen, i.e. the runtime throws 44 an exception, should not be caught with 43 try ... catch because you want to read the 42 message that is thrown in the console.

Try 41 ... catch should IMO be thrown when an exception 40 occurs that your application can foresee 39 in your application logic and you want to 38 perform some custom actions when they do. I.e. you 37 want to be descriptive about it being an 36 exception, and it's not part of the happy 35 flow of the application logic.

For example, you 34 could have a method that validates user 33 input so you could have an isValid method that 32 returns a boolean in which case you would 31 use if ... then.

On the other hand if your 30 performing a certain process, and you know 29 that a certain exception can occur that 28 interrupts the happy flow and you want to 27 handle this, I feel that it is better to 26 throw an exception.

As abstract example, you 25 could have methods that implements some 24 business rules.
Instead of validating every 23 business rule for validity, you could have 22 one custom Exception containing dynamic 21 metadata that can be thrown by each of these 20 methods when validity is breached and handle 19 them appropriately, and continue the happy 18 flow otherwise.
This would translate into 17 something like:

throw new BusinessValidationException(TAG, 'Reason for the validation');

Which IMO is much more descriptive 16 than:

if (!checkValidityBusinessRule()) 
    // doSomething 

For a series of business rules.

As 15 for the example, it's my humble opinion 14 that this check shouldn't be happening in 13 the first place and that the given checks 12 are true by default for implementing the 11 method.

if(typeof jQuery == 'function' && typeof nav == 'object' && typeof pageid != 'undefined' && typeof document.getElementById('leftnav') == 'object')

What it means is that you must 10 declaratively ensure that given conditions 9 are true before invoking the given method 8 with side-effects, taking away the necessity 7 to perform the checks at all.
If it so happens 6 that one of the conditions is false, then 5 it will throw an exception to the console, which 4 is actually what you want because as a developer 3 it means that something in your application 2 logic or lifecycle is broken.

My 2 cents, I 1 hope they make sense.

More Related questions