Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...?
like image 691
CHEBURASHKA Avatar asked Jun 02 '13 15:06

CHEBURASHKA


2 Answers

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.

like image 199
Nick Cox Avatar answered Sep 29 '22 13:09

Nick Cox


You can also prevent the execution of a do file to stop when a error occurs by adding the nostop option to the call:

do myfile, nostop

like image 44
Abramodj Avatar answered Sep 29 '22 13:09

Abramodj