Variable not defined after "try... on error" uses it for error message

I’m super confused by this one. Especially because I believe it used to work until recently.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

set errorMessage to ""
repeat 1 times
	try
	on error errorMessage
	end try
end repeat

if errorMessage is not "" then error errorMessage

Result: Error: The variable errorMessage is not defined.

Script Debugger shows the variable “errorMessage” as being defined with the value being the empty string “” in the sidebar when it errors on the last line, " if errorMessage is not “” then error errorMessage"

It’s definitely the “on error errorMessage” that’s causing the script to think “errorMessage” is undefined. If I change that variable to “someOtherVariableName” it doesn’t error anymore.

Can anybody clarify what’s going on here? I find it very counterintuitive. The “on error” handler isn’t even being called, why is it making my previously defined variable become undefined?

1 Like

Just wondering, when would you ever do this in a script?

1 Like

It looks like something similar to what happens when a command returns no value. The errorMessage variable is being redeclared to be the error message for the try statement’s error handler, except the error is not called.

1 Like
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

set errorMessage to ""
repeat 1 times
	try
	on error e number n
		set errorMessage to e
	end try
end repeat

if errorMessage is not "" then error errorMessage