Suppose you are assembling a .dta file from disparate pieces of raw data -- an .xls workbook here, a .txt file there -- that must each meet some specific conditions. If you do this in a do-file (as you should, for the sake of reproducibility) you will find it useful to first save each of these components into a tempfile and assemble your tempfiles at the end into the .dta file of interest. Tempfiles reside in memory, and die as soon as your do-file has finished running. That is a very convenient way to avoid hard drive clutter.

Now suppose that your final .dta file does not care if some components are not present -- say because you are building it repeatedly, based on data arriving weekly, and it's OK if some of the components are not present in each week. You would want to make this process a server job (cron job if you're UNIX-minded) but for that you would want to ensure that the do-file will not terminate with an error.

Enter capture. Here's how it works:

foreach i in 1 2 { local tempfilei'_ok=0 capture confirm file "tempfilei''" if _rc==0 { local tempfilei'_ok=1 } } 

So I'm assuming you have two files of interest. The confirm file command, unqualified, can check if a file exists, but if it does not it will exit with an error. The capture qualifier stores that error away, in a sense. It sends it to the _rc predefined macro, which is equal to 0 if the file exists, and some other positive integer if it does not. The point of qualifying confirm file by capture is to keep your do-file going. You can store the state of the _rc in the locals tempfilei'_ok shown above, and then based on their values you can do various things with your tempfiles, based on whether they exist:

if tempfile1_ok'==1 & tempfile2_ok'==1 { use "tempfile1'" merge mergevars' using "tempfile2'" tab _merge keep if _merge==3 drop _merge } foreach i in 1/2 { else if tempfilei'_ok==1' { use "tempfilei''" } } save myfinalset, replace } else { display "no tempfiles this week, so moving on" } 

That's it. Now your do-file will run unencumbered. Capture can be used for all sorts of checks.

As an aside, you may have noticed that I merged the two files using the local `mergevars'. It's nice to use local macros for things like combinations of variables, file paths, or file names. Declaring them all at the top of your do-files makes for easier code maintenance and code recycling.