<p>How do I implement a try and except on my python script, I am using the kubernetes python client to communicate with my GKE cluster. And I want to create a deployment if it doesn't exists. I am currently doing this (code below) but it doesn't seem to work as it returns an API exception error and the program crashes.</p>
<p>Here is my current implementation</p>
<pre><code>def get_job():
    conn.connect()
    api = client.CustomObjectsApi()

    for message in consumer:
        message = message.value
        try:
            resource = api.get_namespaced_custom_object(
                        group=&quot;machinelearning.seldon.io&quot;,
                        version=&quot;v1&quot;,
                        name=message[&quot;payload&quot;][&quot;metadata&quot;][&quot;name&quot;],
                        namespace=&quot;seldon&quot;,
                        plural=&quot;seldondeployments&quot;,
                    ) # execution stops here and doesn't move to the next step.
                
            api.create_namespaced_custom_object(
                    group=&quot;machinelearning.seldon.io&quot;,
                    version=&quot;v1&quot;,
                    namespace=&quot;seldon&quot;,
                    plural=&quot;seldondeployments&quot;,
                    body=message['payload'])
            print(&quot;Resource created&quot;)
                    print(e)
            else:
                pass
</code></pre>
<p>How can I fix this?
The logic I am trying to follow is this</p>
<ol>
<li>If the deployment exists, return a already exist message without crashing the script.</li>
<li>If the deployment doesn't exist, create a new deployment.</li>
</ol>

wyn
<blockquote>
<p>I am currently doing this (code below) but it doesn't seem to work as it returns an API exception error and the program crashes.</p>
</blockquote>
<p>The reason it crashes is due to no handling of exception within the code. Your approach also seems flawed. Your try statements can be split into something like this (<a href="https://stackoverflow.com/questions/855759/python-try-else">credit</a>)</p>
<pre><code>try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception
</code></pre>
<p>So what you have to do is add the operations as where they are required to be.</p>
<blockquote>
<p>If the deployment exists, return a already exist message without crashing the script.</p>
</blockquote>
<p>You can handle this in the <code>else</code> statement and simply print a message to state that it already exists.</p>
<blockquote>
<p>If the deployment doesn't exist, create a new deployment.</p>
</blockquote>
<p>You can add this operation within the <code>except</code> part of the try statement, so when an error is thrown it will catch it and perform the operation as you specified.</p>
