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

筅森魡賤 提交于 2019-12-04 02:56:53

问题


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...?

回答1:


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.




回答2:


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




回答3:


One way is to simply insert your code in the command line. Note: you need to prepare it first, and then to copy paste it into the command line. Let's say you have two variables, var1 && var2, and var1 does not exist for your first file, then:

Option 1. your .do file is:

su var1
su var2
...

As you try to execute it you would get the following: variable var1 is not found //and that's all the code stopped

Option 2. you can copy paste the same line into the command field:

su var1
su var2
...

The result is:

. variable var1 is not found
. sum var2

    Variable |       Obs        Mean    Std. Dev.       Min        Max
-------------+--------------------------------------------------------
       var2 |     5              39     26             1         8

. 


来源:https://stackoverflow.com/questions/16884421/does-stata-have-any-try-and-catch-mechanism-similar-to-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!