"on error" vs. "exists" Commands

Is it better to use “on error” or “exists” commands. Lets say I want to create a folder on the desktop.

  1. I can tell “Finder” to check whether the folder exists. If it doesn’t exist, then create a new folder.

  2. I can set the path to the folder as an alias. (A file/folder must exist to be referenced by an alias) If the folder does not exist, then an error is generated. If the error is triggered, then I tell “Finder” to create a new folder.

Here are applescript examples.
Which is of the following code is more efficient.

Using the exists command


property folder_name : "the_folder"

set the_folder to (path to desktop folder as string) & folder_name as string

tell application "Finder"
	
	exists the_folder
	
	if the result is false then
		make new folder at desktop with properties {name:folder_name}
	end if
	
end tell

Using the error trigger


property folder_name : "the_folder"

try
	set the_folder to (path to desktop folder as string) & folder_name as alias
	
on error error_message number error_number
	
	tell application "Finder"
		make new folder at desktop with properties {name:folder_name}
	end tell
	
end try

In my experience, the “error” trigger is slightly faster. What are your thoughts and experiences?

Model: MacBook Pro
AppleScript: 2.3 (118)
Browser: Safari 531.21.10
Operating System: Mac OS X (10.6)

I don’t know which is faster but in general I try to use the Finder as little as possible. I’ve seen the Finder’s spinning beach ball many times and I know the Finder has many responsibilities so it may be busy when you issue it a command… and thus my preference to not use it if possible. As such I prefer the try/error block for your example.

In addition System Events has gotten many new commands over the years, and now it can perform some of the tasks that used to be required of the Finder… so always check if system events can do the task too.

As an example of this… system events also has the “exists” command so if I needed that specific command I would use system events over the Finder.

The other thing to consider is that a number of things can trigger an ‘error’ and therefore run your error handler.

Now, sure, in this case there’s only one command in the try block so it’s pretty easy to work out which command triggered the error but unless you’re going to try every single statement in your code there will be cases where the error handler trips you up.

So in general if there’s a specific condition you’re testing for (e.g. does the folder exist) then I would run that code. Use error handlers for the exceptions so that you can fail gracefully.