Unexpected Exception thrown, even after check.

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
jeff00seattle
Forum Commoner
Posts: 66
Joined: Sat Feb 28, 2009 3:27 pm

Unexpected Exception thrown, even after check.

Post by jeff00seattle »

I have the following code whereby an Exception is thrown even after check.

In this code, if function setupSearchBar() is not defined, then do not call this function:

Code: Select all

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
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Unexpected Exception thrown, even after check.

Post by kaszu »

Because you are trying to access undefined variables value. Following will work:

Code: Select all

if (typeof setupSearchBar == 'function')
Post Reply