Search code examples
executionstata

Is there a way to tell Stata to execute the whole do-file ignoring the lines producing exceptions (or even syntax errors)?


I run the time-consuming code in the background and oftentimes even the 10% of the code is not executed due to a small syntax mistake in the beginning of the do-file.

I would prefer the rest of the do-file to be executed as well since sometimes that mistake in the beginning has no effect on the computations at the end.


Solution

  • (version 2)

    Wanting Stata to ignore mistakes can itself be mistaken.

    1. If there is a mistake early in a do-file, it usually has implications for what follows.

    2. Suppose you got Stata to work as you wish. How do you know whether Stata ignored something important or something trivial? If it ignored something trivial, that should be easy to fix. If it ignored something important, that was the wrong decision.

    Let's now be more constructive. The help for do tells you that there is a nostop option. You need to be very careful about how you use it, but it can help here.

    The context of do, nostop is precisely that of the OP. People had do-files, often expected to take a long time because of big datasets or lots of heavy computation, and set them going, historically "overnight" or "while you went to lunch". Then they would be irritated to find that the do-file had quickly terminated on the first error, and especially irritated if the error was trivial. So, the idea of do, nostop is to do as much as you can, but as an aid to debugging. For example, suppose you got a variable name wrong in various places; you generate Y but refer to y later, which doesn't exist. You might expect to find corresponding error messages scattered through the file, which you can fix. The error messages are the key here.

    The point about do files is that once they are right, you can save yourself lots of time, but no-one ever promised that getting the do-file right in the first place would always be easy.

    My firm advice is: Fix the bugs; don't try to ignore them.

    P.S. capture was mentioned in another answer. capture may seem similar in spirit, but used in similar style it can be a bad idea.

    capture eats error messages, so the user doesn't see them. For debugging, that is the opposite of what is needed.

    capture is really a programmer's command, and its uses are where the programmer is being smart on behalf of the user and keeping quiet about it.

    Suppose, for example, a variable supplied could be numeric or it could be string. If it's numeric, we need to do A; if it's string we need to do B. (Either A or B could be "nothing".) There could be branches like this.

      capture confirm str variable myvar 
      if _rc { /// it's numeric 
           <do A> 
      } 
      else { 
           <do B> 
      } 
    

    Otherwise put, capture is for handling predictable problems if and as they arise. It is not for ignoring bugs.