{"id":59277,"date":"2020-04-30T10:41:44","date_gmt":"2020-04-30T17:41:44","guid":{"rendered":"https:\/\/linuxhint.com\/?p=59277"},"modified":"2020-05-02T07:56:50","modified_gmt":"2020-05-02T14:56:50","slug":"exception_handling_python","status":"publish","type":"post","link":"https:\/\/linuxhint.com\/exception_handling_python\/","title":{"rendered":"Exception Handling in Python"},"content":{"rendered":"<div id=\"wpbody\">\nWhen we run any code that contains error then the error displays in the output by stopping the execution of the program. Some errors may not be recognized by the users and create an undesirable situation for them. But if the error can be displayed in an understandable format for the users then it is easy for them to know the reason for the error. In any object-oriented programming, <strong>try-catch<\/strong> or <strong>try-catch-finally<\/strong> block is used to handle errors and display them in a readable format which is called exception handling. How exception handling can be done in Python script is shown in this tutorial.<\/p>\n<p><strong>Syntax :<\/strong><\/p>\n<div class=\"codecolorer-container python default\" style=\"overflow:auto;white-space:nowrap;width:435px;\"><div class=\"python codecolorer\"><span class=\"kw1\">try<\/span>:<br \/>\n&nbsp; block ...<br \/>\n<span class=\"kw1\">except<\/span> <span class=\"kw2\">Exception<\/span>:<br \/>\n&nbsp; handler ...<br \/>\n<span class=\"kw1\">else<\/span>:<br \/>\n&nbsp; block ...<br \/>\n<span class=\"kw1\">finally<\/span>:<br \/>\n&nbsp; block ...<\/div><\/div>\n<p>Here, if any error occurs while executing the statements of <strong>try <\/strong>block then an exception will be generated and throw the error to the corresponding <strong>except<\/strong> handler. Multiple errors can be generated in a single <strong>try <\/strong>block and then you have to write multiple <strong>except <\/strong>handlers.\u00a0 The statements of the <strong>else <\/strong>block will be executed if no error occurs in the <strong>try<\/strong> block. The statements of the <strong>finally <\/strong>block will be executed if any error occurs or not occurs. For exception handling, using <strong>else <\/strong>and <strong>finally<\/strong> blocks are not essential. Different types of exception handling in python are explained in the next part of the tutorial.<\/p>\n<h3>Example-1: Use of a single try-except block to validate numeric data:<\/h3>\n<p>This example shows the very simple use of exception handling in Python. In the <strong>try <\/strong>block, two inputs will be taken from the user, one is a string value and another is a numeric value.\u00a0 If the user types any string value in place of numeric value for the second input then, the <strong>ValueError<\/strong> exception will be generated by <strong>python3<\/strong> and a custom error message will be displayed from <strong>except<\/strong> block.<\/p>\n<div class=\"codecolorer-container python default\" style=\"overflow:auto;white-space:nowrap;width:780px;\"><div class=\"python codecolorer\"><span class=\"co1\">#!\/usr\/bin\/env python3<\/span><br \/>\n<span class=\"co1\"># Define the try block<\/span><br \/>\n<span class=\"kw1\">try<\/span>:<br \/>\n&nbsp; <span class=\"co1\"># Take any data as a string<\/span><br \/>\n&nbsp; name <span class=\"sy0\">=<\/span> <span class=\"kw2\">input<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;Enter your name: <span class=\"es0\">\\n<\/span>&quot;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># Take any numeric data<\/span><br \/>\n&nbsp; age <span class=\"sy0\">=<\/span> <span class=\"kw2\">int<\/span><span class=\"br0\">&#40;<\/span><span class=\"kw2\">input<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;Enter your age: <span class=\"es0\">\\n<\/span>&quot;<\/span><span class=\"br0\">&#41;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># Print the formatted data with name and age<\/span><br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;Hello %s, You are %s years old.&quot;<\/span> %<span class=\"br0\">&#40;<\/span>name<span class=\"sy0\">,<\/span> age<span class=\"br0\">&#41;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># handle input errors<\/span><br \/>\n<br \/>\n<span class=\"kw1\">except<\/span> <span class=\"br0\">&#40;<\/span><span class=\"kw2\">ValueError<\/span><span class=\"br0\">&#41;<\/span>:<br \/>\n&nbsp; <span class=\"co1\"># Print custom error message<\/span><br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;Wrong input! You have to type a number as your age.&quot;<\/span><span class=\"br0\">&#41;<\/span><\/div><\/div>\n<p><strong>Output:<\/strong><\/p>\n<p>The script is executed two times in the following output with the wrong input and correct input. The first time, when the user type &#8216;<strong>Thirty one\u2019<\/strong> as age value for the second input that takes numeric value then a <strong>ValueError<\/strong> is generated and the error message is displayed from the except block. The second time, no error is generated for correct input values.<\/p>\n<p><a href=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/1-22.jpg\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-59280\" src=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/1-22.jpg\" alt=\"\" width=\"900\" height=\"413\" srcset=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/1-22.jpg 900w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/1-22-300x138.jpg 300w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/1-22-768x352.jpg 768w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/1-22-810x372.jpg 810w\" sizes=\"(max-width: 900px) 100vw, 900px\" \/><\/a><\/p>\n<h3>Example-2: Use of multiple except block to handle multiple errors:<\/h3>\n<p>How you can use multiple except block to handle multiple errors is shown in this example.\u00a0 Two types of errors will be handled in this script. A filename is taken as input from the user for reading. If the file does not exist then it will generate <strong>an IOError<\/strong> exception and if the file exists but empty then it will raise a custom exception. For this, two except blocks are used in this script. When none of the error occurs then the content of the file will be displayed.<\/p>\n<div class=\"codecolorer-container python default\" style=\"overflow:auto;white-space:nowrap;width:780px;height:600px;\"><div class=\"python codecolorer\"><span class=\"co1\">#!\/usr\/bin\/env python3<\/span><br \/>\n<span class=\"co1\"># Import os module<\/span><br \/>\n<span class=\"kw1\">import<\/span> <span class=\"kw3\">os<\/span><br \/>\n<br \/>\n<span class=\"co1\"># Define the try block<\/span><br \/>\n<span class=\"kw1\">try<\/span>:<br \/>\n&nbsp; <span class=\"co1\"># Take the filename as input<\/span><br \/>\n&nbsp; filename <span class=\"sy0\">=<\/span> <span class=\"kw2\">input<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">'Enter a filename<span class=\"es0\">\\n<\/span>'<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># Open the file for reading<\/span><br \/>\n&nbsp; file_handler <span class=\"sy0\">=<\/span> <span class=\"kw2\">open<\/span><span class=\"br0\">&#40;<\/span>filename<span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># Set the seek ponter from 0 to end of the file<\/span><br \/>\n&nbsp; file_handler.<span class=\"me1\">seek<\/span><span class=\"br0\">&#40;<\/span><span class=\"nu0\">0<\/span><span class=\"sy0\">,<\/span> <span class=\"kw3\">os<\/span>.<span class=\"me1\">SEEK_END<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># Read the size of the file in bytes<\/span><br \/>\n&nbsp; size <span class=\"sy0\">=<\/span> file_handler.<span class=\"me1\">tell<\/span><span class=\"br0\">&#40;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"co1\"># Print the file content and the number of characters of the file<\/span><br \/>\n<br \/>\n&nbsp; <span class=\"kw1\">if<\/span><span class=\"br0\">&#40;<\/span>size <span class=\"sy0\">&gt;<\/span> <span class=\"nu0\">0<\/span><span class=\"br0\">&#41;<\/span>:<br \/>\n&nbsp; &nbsp; <span class=\"co1\"># Set the ponter to the starting of the file<\/span><br \/>\n&nbsp; &nbsp; file_handler.<span class=\"me1\">seek<\/span><span class=\"br0\">&#40;<\/span><span class=\"nu0\">0<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; &nbsp; <span class=\"co1\"># Read and store the content of the file in a variable<\/span><br \/>\n&nbsp; &nbsp; file_content <span class=\"sy0\">=<\/span> file_handler.<span class=\"me1\">read<\/span><span class=\"br0\">&#40;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; &nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;<span class=\"es0\">\\n<\/span>The content of the file given below<span class=\"es0\">\\n<\/span>&quot;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; &nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span>file_content<span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; &nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;The size of the file is %d bytes&quot;<\/span>\u00a0 %size<span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; <span class=\"kw1\">else<\/span>:<br \/>\n&nbsp; &nbsp; <span class=\"co1\"># Raise exception if the file is empty<\/span><br \/>\n&nbsp; &nbsp; <span class=\"kw1\">raise<\/span> <span class=\"kw2\">Exception<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">'The file has no content.'<\/span><span class=\"br0\">&#41;<\/span><br \/>\n<br \/>\n<span class=\"co1\"># Print the error message if the file does not exist<\/span><br \/>\n<span class=\"kw1\">except<\/span> <span class=\"kw2\">IOError<\/span> <span class=\"kw1\">as<\/span> error:<br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span>error<span class=\"br0\">&#41;<\/span><br \/>\n<span class=\"co1\"># Print the error message if the file is empty<\/span><br \/>\n<span class=\"kw1\">except<\/span> <span class=\"kw2\">Exception<\/span> <span class=\"kw1\">as<\/span> e:<br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">'Error:%s'<\/span> %e<span class=\"br0\">&#41;<\/span><br \/>\n<span class=\"co1\"># Print the message if there is no error<\/span><br \/>\n<span class=\"kw1\">else<\/span>:<br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">'No error occurs'<\/span><span class=\"br0\">&#41;<\/span><\/div><\/div>\n<p><strong>Output:<\/strong><\/p>\n<p>The script is executed for three times. The first time, a filename is given that does not exist and the output shows an IOError message. The second time, a filename is given that exist but has no content and the output shows a custom message. The third time, a filename is given that exists and contains text. The output shows the content of the file.<\/p>\n<p><a href=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/2-23.jpg\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-59281\" src=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/2-23.jpg\" alt=\"\" width=\"909\" height=\"455\" srcset=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/2-23.jpg 909w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/2-23-300x150.jpg 300w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/2-23-768x384.jpg 768w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/2-23-810x405.jpg 810w\" sizes=\"(max-width: 909px) 100vw, 909px\" \/><\/a><\/p>\n<h3>Example-3: Use of try-except-finally block to handle division error<\/h3>\n<p>The example shows the use of a try-except-finally block to handle division error. Two numeric values will be taken as input and divide the first input by second input in the try block. Two types of errors can occur here. One is <strong>ValueError <\/strong>when the user will type any value without number and another is <strong>ZeroDivisionError<\/strong> when the user will take <strong>0 <\/strong>as a second input.<\/p>\n<div class=\"codecolorer-container python default\" style=\"overflow:auto;white-space:nowrap;width:780px;\"><div class=\"python codecolorer\"><span class=\"co1\">#!\/usr\/bin\/env python3<\/span><br \/>\n<span class=\"co1\"># Define the try block<\/span><br \/>\n<span class=\"kw1\">try<\/span>:<br \/>\n&nbsp; <span class=\"co1\"># Enter two float numbers<\/span><br \/>\n&nbsp; n1 <span class=\"sy0\">=<\/span> <span class=\"kw2\">float<\/span><span class=\"br0\">&#40;<\/span><span class=\"kw2\">input<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">'Enter a number<span class=\"es0\">\\n<\/span>'<\/span><span class=\"br0\">&#41;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n&nbsp; n2 <span class=\"sy0\">=<\/span> <span class=\"kw2\">float<\/span><span class=\"br0\">&#40;<\/span><span class=\"kw2\">input<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">'Enter a number<span class=\"es0\">\\n<\/span>'<\/span><span class=\"br0\">&#41;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n<br \/>\n&nbsp; <span class=\"co1\"># Divide these numbers<\/span><br \/>\n&nbsp; division <span class=\"sy0\">=<\/span> n1 \/ n2<br \/>\n<br \/>\n<span class=\"co1\"># Handle errors<\/span><br \/>\n<span class=\"kw1\">except<\/span> <span class=\"br0\">&#40;<\/span><span class=\"kw2\">ZeroDivisionError<\/span><span class=\"sy0\">,<\/span> <span class=\"kw2\">ValueError<\/span><span class=\"br0\">&#41;<\/span>:<br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;Divided by zero error or The value is not a number&quot;<\/span><span class=\"br0\">&#41;<\/span><br \/>\n<br \/>\n<span class=\"co1\"># Print message if no error occurs<\/span><br \/>\n<span class=\"kw1\">else<\/span>:<br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;The result of the division is %f&quot;<\/span> %division <span class=\"br0\">&#41;<\/span><br \/>\n<span class=\"co1\"># Print message if an error occurs or not occurs<\/span><br \/>\n<span class=\"kw1\">finally<\/span>:<br \/>\n&nbsp; <span class=\"kw1\">print<\/span><span class=\"br0\">&#40;<\/span><span class=\"st0\">&quot;The end&quot;<\/span><span class=\"br0\">&#41;<\/span><\/div><\/div>\n<p><strong>Output:<\/strong><\/p>\n<p>Here, the script is run for two times with both correct inputs and with the second input as 0. So, the second time exception is generated and displays the error message.<\/p>\n<p><a href=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/3-24.jpg\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-59282\" src=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/3-24.jpg\" alt=\"\" width=\"913\" height=\"398\" srcset=\"https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/3-24.jpg 913w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/3-24-300x131.jpg 300w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/3-24-768x335.jpg 768w, https:\/\/linuxhint.com\/wp-content\/uploads\/2020\/04\/3-24-810x353.jpg 810w\" sizes=\"(max-width: 913px) 100vw, 913px\" \/><\/a><\/p>\n<h3>Conclusion:<\/h3>\n<p>This tutorial shows the basic exception handling process in python3 for the new python users. The readers will be able to understand what is exception handling and how to apply in python script after practicing the above examples.\n<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In python, try-catch or try-catch-finally block is used to handle errors and display them in a readable format which is called exception handling. How exception handling can be done in Python script is shown in this tutorial. <\/p>\n","protected":false},"author":33,"featured_media":59304,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1531],"tags":[],"class_list":["post-59277","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/posts\/59277","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/comments?post=59277"}],"version-history":[{"count":0,"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/posts\/59277\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/media\/59304"}],"wp:attachment":[{"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/media?parent=59277"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/categories?post=59277"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/linuxhint.com\/wp-json\/wp\/v2\/tags?post=59277"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}