www.webdeveloper.com
Results 1 to 3 of 3

Thread: Unexpected Exception thrown, even after check.

  1. #1
    Join Date
    Sep 2009
    Posts
    9

    Unexpected Exception thrown, even after check.

    I have the following code whereby an Exception is thrown even after check to prevent an exception from being thrown.

    In this code, if function setupSearchBar() is not defined, then do not call this function:
    Code:
    function setupSearchOnLoad()
    {
      try
      {
        if (setupSearchBar != undefined)
        {
          setupSearchBar();
        }
      }
      catch (ex)
      {
        alert("setupSearchOnLoad: Exception: "+ex.name+": "+ex.message);
      }
    }
    However, what occurs is an Exception is thrown from the if conditional statement because setupSearchBar is not defined:

    Exception.error: ReferenceError
    Exception.message: "setupSearchBar is not defined"


    Why would this occur?

    Jeff in Seattle

  2. #2
    Join Date
    Feb 2006
    Posts
    2,926
    It is usually an error to use an undeclared variable in an expression.

    You could use the typeof operator, which is made to handle undeclared types as undefined.

    if(typeof setupSearchBar !='undefined')

    If it is a global you could reference it to the window-

    if(window.setupSearchBar)

  3. #3
    Join Date
    Sep 2009
    Posts
    9
    Works like a charm! Thanks for the feedback!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles