Search code examples
javatry-catchstata

Does Stata have any `try and catch` mechanism similar to Java?


I am writing a .do to check the existence of some variables in a number of .dta files as well as to check the existence of certain values for those variables. However, my code stops executing as it encounters an invalid variable name.

I know I mix Java and Stata coding, and it is completely inappropriate, but is there any way I could do something like:

try {
su var1
local var1_mean=(mean)var1
local var1_min=(min)var1
local var1_max=(max)var1
...
}
catch (NoSuchVariableException e) {
System.out.println("Var1 does not exist")
}
// So that the code does not stop executing...?

Solution

  • The short answer is Yes. A slightly longer answer is that guessing what the syntax might be by analogy with Java has minimal chance of success. It is best to read Stata's documentation, e.g. start by skimming the main entries in the [P] manual.

    Here the problem being trapped is that no var1 exists. This code is legal, or so I trust:

    capture su var1, meanonly 
    
    if _rc == 0 { 
         local var1_mean = r(mean)
         local var1_min  = r(min)
         local var1_max  = r(max)
    }
    else display "var1 does not exist"
    

    The idea is two-fold. capture eats any error of the command it prefixes, but a return code will still be accessible in _rc. Non-zero return codes are error codes.

    A related command is confirm, e.g.

    capture confirm var var1 
    

    checks that a variable var1 exists.