Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Catch and Print Exception Messages in Python

#1
How to Catch and Print Exception Messages in Python

<div><p>Python comes with an extensive support of exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the <a href="https://blog.finxter.com/python-indexerror-list-index-out-of-range/" title="Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)" target="_blank" rel="noreferrer noopener"><code>IndexError</code></a>, <a href="https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/" title="How to Fix “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”" target="_blank" rel="noreferrer noopener"><code>ValueError</code></a>, and <code><a href="https://blog.finxter.com/python-typeerror-nonetype-object-is-not-subscriptable/" target="_blank" rel="noreferrer noopener" title="Python TypeError: Object is Not Subscriptable (How to Fix This Stupid Bug)">TypeError</a></code>. </p>
<p>An exception will immediately terminate your program. To avoid this, you can <strong>catch the exception</strong> with a <code>try/except</code> block around the code where you expect that a certain exception may occur. Here’s how you <strong>catch and print a given exception:</strong></p>
<p class="has-pale-cyan-blue-background-color has-background">To catch and print an exception that occurred in a code snippet, wrap it in an indented <code>try</code> block, followed by the command <code>"except Exception as e"</code> that catches the exception and saves its error message in string variable <code>e</code>. You can now print the error message with <code>"print(e)"</code> or use it for further processing.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try: # ... YOUR CODE HERE ... #
except Exception as e: # ... PRINT THE ERROR MESSAGE ... # print(e)
</pre>
<h2>Example 1: Catch and Print IndexError</h2>
<p>If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an <code>IndexError</code> telling you that the list<a href="https://blog.finxter.com/python-indexerror-list-index-out-of-range/" target="_blank" rel="noreferrer noopener" title="Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)"> index is out of range</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try: lst = ['Alice', 'Bob', 'Carl'] print(lst[3])
except Exception as e: print(e) print('Am I executed?')
</pre>
<p>Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist!</p>
<figure class="wp-block-image"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/05/indexing-1024x576.jpg" alt="" class="wp-image-8937" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/indexing-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>Fortunately, you wrapped the code in a <code>try/catch</code> block and printed the exception. The program is not terminated. Thus, it executes the final <code><a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" target="_blank" rel="noreferrer noopener" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]">print()</a></code> statement after the exception has been caught and handled. This is the output of the previous code snippet.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">list index out of range
Am I executed?</pre>
<h2>Example 2: Catch and Print ValueError</h2>
<p>The<a href="https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/" target="_blank" rel="noreferrer noopener" title="How to Fix “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”"> <code>ValueError</code></a> arises if you try to use wrong values in some functions. Here’s an example where the <code>ValueError</code> is raised because you tried to calculate the square root of a negative number:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math try: a = math.sqrt(-2)
except Exception as e: print(e) print('Am I executed?')</pre>
<p>The output shows that not only the error message but also the string <code>'Am I executed?'</code> is printed.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">math domain error
Am I executed?</pre>
<h2>Example 3: Catch and Print TypeError</h2>
<p>Python throws the <code><a href="https://blog.finxter.com/python-typeerror-nonetype-object-is-not-subscriptable/" title="Python TypeError: Object is Not Subscriptable (How to Fix This Stupid Bug)">TypeError </a>object is not subscriptable</code> if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn’t define the <code>__getitem__()</code> method. Here’s how you can catch the error and print it to your shell:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try: variable = None print(variable[0])
except Exception as e: print(e) print('Am I executed?')
</pre>
<p>The output shows that not only the error message but also the string <code>'Am I executed?'</code> is printed.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">'NoneType' object is not subscriptable
Am I executed?</pre>
<p>I hope you’re now able to catch and print your error messages. </p>
<h2>Summary</h2>
<p>To catch and print an exception that occurred in a code snippet, wrap it in an indented <code>try</code> block, followed by the command <code>"except Exception as e"</code> that catches the exception and saves its error message in string variable <code>e</code>. You can now print the error message with <code>"print(e)"</code> or use it for further processing.</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</p>
<p>The post <a href="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" target="_blank" rel="noopener noreferrer">How to Catch and Print Exception Messages in Python</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/11/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016