{"id":2956,"date":"2018-03-18T08:33:11","date_gmt":"2018-03-18T08:33:11","guid":{"rendered":"http:\/\/truelogic.org\/wordpress\/?p=2956"},"modified":"2018-03-20T05:06:50","modified_gmt":"2018-03-20T05:06:50","slug":"python-2-7-fundamentals-exceptions","status":"publish","type":"post","link":"https:\/\/truelogic.org\/wordpress\/2018\/03\/18\/python-2-7-fundamentals-exceptions\/","title":{"rendered":"Python 2.7 &#8211; Fundamentals &#8211; Exceptions"},"content":{"rendered":"<h3>Using Source Files<\/h3>\n<p>Till now we have been using the python interpreter and entering code directly on the command line. From this point, we will use source code files and run them via the python compiler.<\/p>\n<ul>\n<li>Use any text editor of your choice and type in the code<\/li>\n<li>Save your file giving it a name and a .py extension<\/li>\n<li>From the command line type <em>python yourfile.py<\/em><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<h3>Runtime Exceptions<\/h3>\n<p>Any program will have errors. There are two kinds of errors:<\/p>\n<ul>\n<li>Syntax errors<\/li>\n<li>Runtime Exceptions<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>Syntax errors are errors which python shows when you ask it to run some code. These errors happen because the code does not follow the rules of syntax of Python. Examples are given below:<\/p>\n<pre>&gt;&gt;&gt; \r\n&gt;&gt;&gt; print 10 + \"word\"\r\nTraceback (most recent call last):\r\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\r\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\r\n&gt;&gt;&gt; print 10 \/ 0\r\nTraceback (most recent call last):\r\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\r\nZeroDivisionError: integer division or modulo by zero\r\n&gt;&gt;&gt; c = a + * b\r\n File \"&lt;stdin&gt;\", line 1\r\n c = a + * b\r\n ^\r\nSyntaxError: invalid syntax\r\n&gt;&gt;&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p>Syntax errors are easy to spot since Python itself points it out. Your programs will not run if they have syntax errors.<\/p>\n<p>Runtime Exceptions are errors which occur during the execution of the code. This can happen due to various conditions. Some examples are given below:<\/p>\n<pre>set1 = {1,2,3,4,5,6}\r\nset2 = None\r\n\r\nprint set1.intersection(set2)<\/pre>\n<pre><\/pre>\n<p>Output:<\/p>\n<pre>Traceback (most recent call last):\r\n File \"exceptions.py\", line 6, in &lt;module&gt;\r\n print set1.intersection(set2)\r\nTypeError: 'NoneType' object is not iterable\r\n\r\n<\/pre>\n<p>Python provides a way of handling Exceptions in your code so that you can handle it as required and not have the program crash. When an exception is <em>raised<\/em>\u00a0 you can <em>handle <\/em> it using the <em>try except<\/em> control structure. Each kind of Exception has a name and there are many Exceptions predefined in Python eg. TypeError. RangeError, NameError etc.<\/p>\n<p>At its basic usage a <em>try except <\/em>can be set to handle any Exception which occurs within its statements as shown below:<\/p>\n<pre>set1 = {1,2,3,4,5,6}\r\nset2 = None\r\n\r\ntry:\r\n print set1.intersection(set2)\r\nexcept:\r\n print \"Exception handled\"<\/pre>\n<p>Output:<\/p>\n<pre>Exception handled<\/pre>\n<p>We executed the same code above with a <em>try except<\/em> statement. But we can be more specific about what exception we want to handle by adding the name of the Exception to the control structure:<\/p>\n<pre>set1 = {1,2,3,4,5,6}\r\nset2 = None\r\n\r\ntry:\r\n print set1.intersection(set2)\r\nexcept TypeError:\r\n print \"Exception handled\"<\/pre>\n<p>Output:<\/p>\n<pre>Exception handled<\/pre>\n<p>If you put the wrong Exception name then it will not work:<\/p>\n<pre>set1 = {1,2,3,4,5,6}\r\nset2 = None\r\n\r\ntry:\r\n print set1.intersection(set2)\r\nexcept NameError:\r\n print \"Exception handled\"<\/pre>\n<p>Output:<\/p>\n<pre>Traceback (most recent call last):\r\n File \"exceptions.py\", line 7, in &lt;module&gt;\r\n print set1.intersection(set2)\r\nTypeError: 'NoneType' object is not iterable<\/pre>\n<p>You can handle multiple Exceptions within a <em>try except <\/em>block by passing the exception names within brackets. Assigning a variable to the Exception allows you to examine the actual Exception which was handled.<\/p>\n<p>Note that if you are catching multiple Exceptions then only one of them will be caught &#8211; whichever one happens first. Once execution enters into the <em>except <\/em>block then it will not go back and execute the rest of the statements within the <em>try <\/em>section.<\/p>\n<p>&nbsp;<\/p>\n<pre>set1 = {1,2,3,4,5,6}\r\nset2 = None\r\n\r\ntry:\r\n print 12\/0\r\n print set1.intersection(set2)\r\nexcept (TypeError, ZeroDivisionError) as err:\r\n print \"Exception handled \" \r\n print err<\/pre>\n<p>Output:<\/p>\n<pre>Exception handled \r\ninteger division or modulo by zero<\/pre>\n<p>As you can see above, the division by zero exception was handled and then it exited the <em>try except <\/em>block without executing the <em>set1.intersection(set2) <\/em>statement.<\/p>\n<p>In the next post, we examine <a href=\"https:\/\/truelogic.org\/wordpress\/2018\/03\/20\/python-2-7-fundamentals-files-directories-directory-management\/\" target=\"_blank\" rel=\"noopener\">Directory Management<\/a>.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Using Source Files Till now we have been using the python interpreter and entering code directly on the command line. From this point, we will <a class=\"mh-excerpt-more\" href=\"https:\/\/truelogic.org\/wordpress\/2018\/03\/18\/python-2-7-fundamentals-exceptions\/\" title=\"Python 2.7 &#8211; Fundamentals &#8211; Exceptions\">[&#8230;]<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":2107,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[297],"tags":[],"class_list":["post-2956","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/2956","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/comments?post=2956"}],"version-history":[{"count":10,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/2956\/revisions"}],"predecessor-version":[{"id":3111,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/2956\/revisions\/3111"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media\/2107"}],"wp:attachment":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media?parent=2956"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/categories?post=2956"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/tags?post=2956"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}