try ... on error: default error number

Greetings!


try
	display alert "Hello" buttons {"Cancel", "OK"} cancel button 1
on error errText number errNum
	if (errNum is equal to -128) then
		-- User cancelled. 
		display dialog "User cancelled."
	else
		display dialog "Some other error: " & errNum & return & errText
	end if
end try

display dialog "Error: " & errNum

If you push Cancel button you get error messages, but if you push OK button you get the following error message:

The variable errNum is not defined.

Could you help me please to figure out the way to define a default value for errNum variable, for example 0, in case of no error has occurred?

I am a bit surprised about the conditional scoping behavior that you have discovered for the error handler error message and error number variables. I would have thought that their scope would have been limited to the error handler itself, but it appears that such variables are “promoted” as local variables to the enclosing local-level scope (i.e. the implicit run handler in this case). Sort of.

Anyway, if you want to see the error number and message values outside of the error handler, you could save them in some other (initialized) variable that has an unconditional scope.

set err to missing value

try
	display alert "Hello" buttons {"Cancel", "OK"} cancel button 1
	error "A forced error!" number 123 -- no error later whether this is commented out or not
on error errText number errNum
	if (errNum is equal to -128) then
		-- User cancelled. 
		display dialog "User cancelled."
	else
		display dialog "INNER Some other error: " & errNum & return & errText
		set err to {errNum, errText}
	end if
end try

if err is not missing value then
	set {errNum, errText} to err
	display dialog "OUTER Some other error: " & errNum & return & errText
end if

Predeclaring the variables as local also seems to work:

local n, m
set {n, m} to {missing value, missing value}
try
	--error "foo" number 1
on error m number n
end try
{n, m} --> {missing value,missing value} OR {1,"foo"}

Model: iBook G4 933
AppleScript: 1.10.7
Browser: Safari 4.0.2 (4530.19)
Operating System: Mac OS X (10.4)

Thank you, Chrys!
I usualy initialize new variables using set or copy, but now I’ll pay attention on local and global variables.