title: How do I catch error and write to strerr with letting the program break
body: <p>Let's say I have a program that runs continuously, waiting for order from a program with standard input. The method that keeps waiting for order is called &quot;run&quot; using while.</p>
  <p><a href="https://i.stack.imgur.com/UejLU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UejLU.png" alt="" /></a></p>
  
  <p>As you see, when run() gets certain order, they pass the order to certain function.</p>
  <p>When I run the program, every time I give a command that can cause an error (say: Index error), it breaks and shut down (obviously)</p>
  <p>I decided to try to catch the error with <code>try/except</code></p>
  <pre><code>def a(order):
      try:
          &lt;some algorithm&gt;
          return something
      except Exception, error:
          stderr.write(error)
          stderr.flush()
  def b(order):
      try:
          &lt;some algorithm&gt;
          return something
      except Exception, error:
          stderr.write(error)
          stderr.flush()
  def run(order)
      while stdin.notclosed:
          try:
              read stdin
              if stdin==specific order :
                  x=a(stdin order)
              else:
                  x=b(stdin order)
          except Exception,error:
              stderr.write(error)
              stderr.flush()
  run()
  </code></pre>
  <p>However, it seems the program that gives the order can't read the error. From my analyst, it seems the program that gives order only start reading <code>stderr</code> after the program that reads the order ends. However, due to <code>try/catch</code>, the program never ends. Is there anyway that to catch the error, write it, then end it. (The error can came from any function)</p>
  <p>PS: Let's assume you can't modify or read the program that gives order. (This is competition, the reason I said this, is since that when I access the <code>stderr</code>, it's empty.)</p>