Search code examples
stata

Capture does not work when used with several commands


I have more than 3,000 variables and labels in my do file, but in my dataset I need ~300 of the labels. To bypass the errors of not having the variables, I used the capture command.

In my data, there are no hhid or hh_cu_q variables and there is only a newid variable:

capture noisily {
    label var hhid "Identifier for household with more than one CU. Household with only one CU will be set to missing."
    label var hh_cu_q "Count of Consumer Units in this household"
    label var newid "Public use microdata identifier"
}

However, when I run this code, I see the error for the first line of the command (variable hhid not found), and it seems that Stata is executing the rest of the lines, but there is no change in the label!

If I run only the last line of the command it works fine (it adds the label for newid).


Solution

  • This is normal behavior because you are applying capture in an entire block of commands. As a result, when an error arises, Stata bypasses all remaining commands in the block and moves on to executing the rest of the do file.

    When applying capture individually everything works as you expect:

    clear
    set obs 1
    
    generate newid = .
    
    . capture noisily label var hhid "Identifier for household with more than one CU. Household with only one CU will be set to missing."
    variable hhid not found
    
    . capture noisily label var hh_cu_q "Count of Consumer Units in this household"
    variable hh_cu_q not found
    
    . capture noisily label var newid "Public use microdata identifier"
    
    . display "`: variable label newid'"
    Public use microdata identifier