<p>With Kubernetes Container running a Python script:</p>

<pre><code>import time
while True:
    try:
        for i in range(10):
            if i==0:
                raise Exception('Exception occurred!')
    except:
        pass
    time.sleep(1)
</code></pre>

<p>I would like to pass the Exception's message <code>'Exception occurred!'</code> down to the Container so this error message could be seen with:</p>

<p><code>kubectl describe pod pod_id</code></p>

<p>Would it be possible?</p>

<p>Anything you <code>print()</code> will be visible in <code>kubectl logs</code>.  (You may need to set an environment variable <code>PYTHONUNBUFFERED=1</code> in your pod spec.)</p>

<p>Your code as you've written it will never print anything.  The construct</p>

<pre class="lang-py prettyprint-override"><code>try:
  ...
except:
  pass
</code></pre>

<p>silently ignores any and all exceptions out of the <code>try</code> block.  The bare <code>except:</code> even captures some system-level exceptions like <code>SystemExit</code> or <code>KeyboardInterrupt</code>; this is almost always wrong.  Often you want your <code>except</code> blocks to be as tightly scoped as you can, and the Python tutorial on <a href="https://docs.python.org/3/tutorial/errors.html#tut-userexceptions" rel="noreferrer">user-defined exceptions</a> is a helpful pattern.</p>

<p>(The exception to this, particularly in a Kubernetes context, is that you will often want a very broad exception handler to do something like return an HTTP 500 error to a network request, rather than crashing the application.)</p>

<p>A better example might look like:</p>

<pre class="lang-py prettyprint-override"><code>import time

class OneException(Exception):
  pass

def iteration():
  for i in range(10):
    try:
      if i == 1:
        raise OneException("it is one")
      print(i, math.sqrt(i), math.sqrt(-i))
      # will work when i==0 but fail when i==2
    except OneException as e:
      print(i, repr(e))
      # and proceed to the next iteration

if __name__ == '__main__':
  while True:
    # The top-level loop.  We want a very broad catch here.
    try:
      iteration()
    except Exception as e:
      print('iteration failed', repr(e))
    time.sleep(1)
</code></pre>
