{"id":121071,"date":"2020-11-23T11:12:49","date_gmt":"2020-11-23T11:12:49","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=17194"},"modified":"2020-11-23T11:12:49","modified_gmt":"2020-11-23T11:12:49","slug":"how-to-catch-and-print-exception-messages-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/11\/23\/how-to-catch-and-print-exception-messages-in-python\/","title":{"rendered":"How to Catch and Print Exception Messages in Python"},"content":{"rendered":"<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 \u201cValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\u201d\" 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>\n<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&#8217;s how you <strong>catch and print a given exception:<\/strong><\/p>\n<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>\n<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 ... #\nexcept Exception as e: # ... PRINT THE ERROR MESSAGE ... # print(e)\n<\/pre>\n<h2>Example 1: Catch and Print IndexError<\/h2>\n<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>\n<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])\nexcept Exception as e: print(e) print('Am I executed?')\n<\/pre>\n<p>Your genius code attempts to access the fourth element in your list with index 3&#8212;that doesn&#8217;t exist!<\/p>\n<figure class=\"wp-block-image\"><img decoding=\"async\" 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\/uploads\/2020\/05\/indexing-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/indexing-768x432.jpg 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<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>\n<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\nAm I executed?<\/pre>\n<h2>Example 2: Catch and Print ValueError<\/h2>\n<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 \u201cValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\u201d\"> <code>ValueError<\/code><\/a> arises if you try to use wrong values in some functions. Here&#8217;s an example where the <code>ValueError<\/code> is raised because you tried to calculate the square root of a negative number:<\/p>\n<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)\nexcept Exception as e: print(e) print('Am I executed?')<\/pre>\n<p>The output shows that not only the error message but also the string <code>'Am I executed?'<\/code> is printed.<\/p>\n<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\nAm I executed?<\/pre>\n<h2>Example 3: Catch and Print TypeError<\/h2>\n<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\u2019t define the <code>__getitem__()<\/code> method. Here&#8217;s how you can catch the error and print it to your shell:<\/p>\n<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])\nexcept Exception as e: print(e) print('Am I executed?')\n<\/pre>\n<p>The output shows that not only the error message but also the string <code>'Am I executed?'<\/code> is printed.<\/p>\n<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\nAm I executed?<\/pre>\n<p>I hope you&#8217;re now able to catch and print your error messages. <\/p>\n<h2>Summary<\/h2>\n<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>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<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 IndexError, ValueError, and TypeError. An exception will immediately terminate your program. To avoid this, you can catch the exception with a try\/except block around the code [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-121071","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/121071","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=121071"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/121071\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=121071"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=121071"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=121071"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}