Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Catching exceptions in Stata; capturing everything?

    Hello everyone,

    I'm trying to learn Stata, having a background in general programming. I have a small question about the best practice for catching exceptions in Stata. Suppose I want to do get a varlist with all the variables starting with p in my dataset, if they are any. I would do:

    Code:
    ds p*
    Now suppose there is no such variable, I would get the following error:

    Code:
    ds p*
    variable p* not found
    r(111);
    The solution I see the most frequently on Statalist and other forums to this type of problem is the following

    Code:
    capture ds p*
    if _rc {
        *do something if no p*
    }
    else {
        *do something with the p* variables
    }
    To me, there is a problem here; "if _rc" catches any exceptions. This is discouraged in other programming languages because if some other unexpected error occurs in you code, you don't see it until something breaks later in the code. We know we expect a r(111) exception, so the way I would "intuitively" write it would be:

    Code:
    capture ds p*
    if _rc == 111 {
        *do something if no p*
    }
    else if _rc == 0 {
        *do something with the p* variables
    }
    else {
        * return the error code and exits the do-file execution
        error _rc
        exit
    }
    How come Stata programmers use the former? Am I missing something? Thank you very much!
    Last edited by Baptiste Ottino; 24 May 2018, 09:39. Reason: english

  • #2
    How come Stata programmers use the former? Am I missing something?
    Well, I think you are over-generalizing. It is true that the simple approach you mention is often shown here. But examples that are more careful about distinguishing the expected problem from the unexpected can also be found here. My own posts that use -capture- typically follow the practice you are recommending, for example.

    Comment


    • #3
      Well, I think you are over-generalizing.
      I certainly am. I haven't seen a case of specific exception catching yet, so I wrongly assumed that the best practice was to capture everything. I was thinking that maybe capture worked in a different way than classical try/catch statements. But if you say that it makes sense to capture specific error codes, I'll definitely do it your way. Thank you for your answer!

      Comment

      Working...
      X