title: AppleScript: strange error about non-defined variable
body: <p>Sometimes, I get this error:</p>
  
  <p><code>./mac/get_foregroundapp_info.scpt:254:265: execution error: The variable window_name is not defined. (-2753)</code></p>
  
  <p>This is strange because I cannot see how the variable is not defined. This is the code:</p>
  
  <pre><code>global frontApp, frontAppName, idleTime, window_name
  
  tell application "System Events"
      set frontApp to first application process whose frontmost is true
  end tell
  
  set window_name to ""
  try
      set window_name to name of front window of frontApp
  end try
  if window_name = missing value then
      set window_name to ""
  end if
  </code></pre>
  
  <p>The error appears in the line <code>if window_name ...</code>.</p>
  
  <p>But it appears only rarely, maybe in about 2-5% of the cases.</p>
  
  <p>It seems to appear more often / always (?) when I keep the Command-key pressed down and mouse hold over some link in Chrome. No idea if that is completely random behavior now or in any way related.</p>
  
  <hr>
  
  <p>Edit: It seems to appear also always when I have an image opened with Preview. Strangely it seems to work if I open a PDF with Preview.</p>
  
  <hr>
  
  <p>As Chuck pointed out, it is possible to catch this 'undefined-variable'-error with another <code>try</code> block.</p>
  
  <p>But my main question actually here is: Why is the variable undefined? What does that mean? Because as I see it, it must be defined at that place.</p>
  
  <hr>
  
  <p>(Btw., this code about getting the window title has several drawbacks. One of them is described here. It also doesn't always work because of this. See another solution <a href="https://stackoverflow.com/questions/5292204/macosx-get-foremost-window-title/5293758#5293758">here</a> which seems to always work and also without such strange errors.)</p>