Stata是否有类似Java的“try and catch”机制? [英] Does Stata have any `try and catch` mechanism similar to Java?

查看:242
本文介绍了Stata是否有类似Java的“try and catch”机制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 .do 来检查一些 .dta 文件中是否存在某些变量以及检查这些变量的某些值是否存在。但是,我的代码在遇到无效的变量名时停止执行。

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.

我知道我混合了Java和Stata编码,这是完全不合适的,但有什么办法我可以做类似的事情:

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


推荐答案

简短回答是肯定的。稍微长一点的答案是,通过类比Java来猜测语法可能是成功的最小机会。最好阅读Stata的文档,例如首先浏览[P]手册中的主要条目。

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.

这里遇到的问题是没有 var1 存在。这段代码是合法的,或者我相信:

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"

这个想法是双重的。 capture 吃掉它前缀命令的任何错误,但仍然可以在 _rc 中访问返回码。非零返回码是错误代码。

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.

相关命令是 confirm ,例如

capture confirm var var1 

检查变量 var1 是否存在。

这篇关于Stata是否有类似Java的“try and catch”机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆