{"id":1908,"date":"2019-06-12T23:02:48","date_gmt":"2019-06-12T23:02:48","guid":{"rendered":"http:\/\/wiki.thomasandsofia.com\/?p=1908"},"modified":"2019-06-13T00:05:54","modified_gmt":"2019-06-13T00:05:54","slug":"section-10-errors-and-exception-handling","status":"publish","type":"post","link":"https:\/\/wiki.thomasandsofia.com\/?p=1908","title":{"rendered":"Section 10: Errors and Exception Handling"},"content":{"rendered":"<p><a href=\"http:\/\/wiki.thomasandsofia.com\/?p=1901\">&lt; Section 9<\/a> | Section 11<\/p>\n<h1>Errors and Exception Handling<\/h1>\n<p><a href=\"https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478394#questions\" target=\"_blank\" rel=\"noopener\">https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478394#questions<\/a><\/p>\n<ul>\n<li>Errors are bound to happen &#8211; especially when someone else uses it in an unexpected way<\/li>\n<li>Error handling is used in an attempt to plan for these errors<\/li>\n<li>Example:\n<ul>\n<li>Someone tries to write to a file only opened mode=&#8217;r&#8217;<\/li>\n<li>Without error handling, the entire script would stop.<\/li>\n<li>Error handling allows the script to continue even if there is an error.\n<ul>\n<li>it also reports the error<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2>try, except, and finally<\/h2>\n<ul>\n<li>try: This is a block of code to be attempted (that may lead to an error)<\/li>\n<li>except: Block of code will execute in case there is an error in the try block<\/li>\n<li>finally: A block of code to be executed regardless of an error.<\/li>\n<\/ul>\n<pre>def add(n1, n2):\r\n    return n1 + n2\r\nn1=20\r\nn2=input(\"Enter a number: \")\r\nprint(\"sum of {} and {} is \"+add(n1,n2))\r\n<\/pre>\n<p>Enter a number: 10<br \/>\nTypeError: unsupported operand type(s) for +: &#8216;int&#8217; and &#8216;str&#8217;<\/p>\n<h3>Using Error handling<\/h3>\n<pre>def add(n1, n2):\r\n    try:\r\n        result = n1 + n2\r\n    except:\r\n        # somefunction log error\r\n        return False\r\n    else:\r\n        # only runs when not an error\r\n        return result\r\nn1=20\r\nn2=input(\"Enter a number: \")\r\nprint(\"sum of {} and {} is {}\".format(n1, n2, add(n1,n2)))<\/pre>\n<p>Enter a number: 10<br \/>\nsum of 20 and 10 is False<\/p>\n<h2>Using finally<\/h2>\n<p>I don&#8217;t see how this is different than just adding a line of code under the try\/except block&#8230;<\/p>\n<pre>try:\r\n   f=open('testfile','r')\r\n   f.write('write a test line')\r\nexcept OSError:\r\n    print(\"OS Error!\")\r\nexcept TypeError:\r\n    # not going to happen, just an example\r\n    pass\r\nexcept:\r\n    # all non-explicit exceptions\r\n    pass\r\nfinally:\r\n    print(\"I always run.\")<\/pre>\n<p>OS Error!<br \/>\nI always run.<\/p>\n<h2>Full Example<\/h2>\n<pre>def ask4int():\r\n    while 1:\r\n        try:\r\n            result = int(input(\"Please enter a number: \"))\r\n        except:\r\n            print(\"Whoops! That was not a number!\")\r\n            continue\r\n        else:\r\n            print(\"Thank you!\")\r\n            break\r\n        finally:\r\n            print(\"End of try\/except\/finally\")\r\n            print(\"I will ALWAYS run at the end!\")\r\nask4int()<\/pre>\n<p>Please enter a number: a<br \/>\nWhoops! That was not a number!<br \/>\nEnd of try\/except\/finally<br \/>\nI will ALWAYS run at the end!<br \/>\nPlease enter a number: 2<br \/>\nThank you!<br \/>\nEnd of try\/except\/finally<br \/>\nI will ALWAYS run at the end!<\/p>\n<h1>Errors and Exceptions Homework<\/h1>\n<p><a href=\"https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478396#questions\" target=\"_blank\" rel=\"noopener\">https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478396#questions<\/a><\/p>\n<p>&nbsp;<\/p>\n<h1>Errors and Exceptions Solutions<\/h1>\n<p><a href=\"https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478404#questions\" target=\"_blank\" rel=\"noopener\">https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478404#questions<\/a><\/p>\n<p>&nbsp;<\/p>\n<h1>Pylint Overview<\/h1>\n<p><a href=\"https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478414#questions\" target=\"_blank\" rel=\"noopener\">https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478414#questions<\/a><\/p>\n<p>There are several testing tools.\u00a0 We will focus on two:<\/p>\n<ul>\n<li>pylint\n<ul>\n<li>This is a library that looks at your code and reports back possible issues and provides a score (10\/10 is the best)<\/li>\n<li>This is usually used with larger organizations with various teams of developers to ensure coding standards are met.<\/li>\n<\/ul>\n<\/li>\n<li>unittest\n<ul>\n<li>This is a built-in library that will allow you to test your programs and check you are getting the desired outputs<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Pylint checks for code errors and styling (PEP 8)<\/p>\n<h3>Install Pylint<\/h3>\n<p>Use the command line and text editor for these examples<\/p>\n<pre>CMD: pip install pylint<\/pre>\n<p>Simple1.py<\/p>\n<pre>a = 1\r\nb = 2\r\nprint(a)\r\nprint(B)<\/pre>\n<pre>CMD: pylint simple1.py<\/pre>\n<p>************* Module simple1<br \/>\nsimple1.py:4:0: C0304: Final newline missing (missing-final-newline)<br \/>\nsimple1.py:1:0: C0111: Missing module docstring (missing-docstring)<br \/>\nsimple1.py:1:0: C0103: Constant name &#8220;a&#8221; doesn&#8217;t conform to UPPER_CASE naming style (invalid-name)<br \/>\nsimple1.py:2:0: C0103: Constant name &#8220;b&#8221; doesn&#8217;t conform to UPPER_CASE naming style (invalid-name)<br \/>\nsimple1.py:4:6: <strong>E<\/strong>0602: Undefined variable &#8216;B&#8217; (undefined-variable)<\/p>\n<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nYour code has been rated at -12.50\/10<\/p>\n<pre>'''\r\nA very simple script\r\n'''\r\ndef func():\r\n    '''\r\n    my simple function\r\n    '''\r\n    first = 1\r\n    second = 2\r\n    print(first)\r\n    print(second)\r\nfunc()\r\n<\/pre>\n<pre>CMD: pylint simple1.py<\/pre>\n<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br \/>\nYour code has been rated at 8.33\/10 (previous run: 10\/10, +22.5)<\/p>\n<h1>Running tests with the Unittest Library<\/h1>\n<p><a href=\"https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478416#questions\" target=\"_blank\" rel=\"noopener\">https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478416#questions<\/a><\/p>\n<p>Create 2 files<\/p>\n<ul>\n<li>caps.py<\/li>\n<li>test_caps.py<\/li>\n<\/ul>\n<h3>Failure test<\/h3>\n<p>caps.py<\/p>\n<pre>def cap_text(text):\r\n    '''\r\n    returns the capitalized version of a string.\r\n    '''\r\n    return text.capitalize()<\/pre>\n<p>test_caps.py<\/p>\n<pre>import unittest\r\nimport caps\r\n\r\nclass TestCap(unittest.TestCase):\r\n    def test_one_word(self):\r\n        text = 'python'\r\n        result = caps.cap_text(text)\r\n        self.assertEqual(result, 'Python')\r\n    def test_one_word(self):\r\n        text = 'monte python'\r\n        result = caps.cap_text(text)\r\n        self.assertEqual(result, 'Monte Python')\r\n\r\nif __name__ == '__main__':\r\n    unittest.main()<\/pre>\n<pre>CMD: python test_caps.py<\/pre>\n<p>F<br \/>\n======================================================================<br \/>\nFAIL: test_one_word (__main__.TestCap)<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nTraceback (most recent call last):<br \/>\n  File &#8220;test_caps.py&#8221;, line 12, in test_one_word<br \/>\n    self.assertEqual(result, &#8216;Monte Python&#8217;)<br \/>\nAssertionError: &#8216;Monte python&#8217; != &#8216;Monte Python&#8217;<br \/>\n&#8211; Monte python<br \/>\n?       ^<br \/>\n+ Monte Python<br \/>\n?       ^<\/p>\n<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nRan 1 test in 0.002s<\/p>\n<p>FAILED (failures=1)<\/p>\n<h3>Failure resolved<\/h3>\n<p>caps.py<\/p>\n<pre>def cap_text(text):\r\n    '''\r\n    returns the capitalized version of a string.\r\n    '''\r\n    return text.title()<\/pre>\n<pre>CMD: python test_caps.py<\/pre>\n<p>.<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nRan 1 test in 0.002s<\/p>\n<p>OK<br \/>\n&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>&lt; Section 9 | Section 11 Errors and Exception Handling https:\/\/www.udemy.com\/complete-python-bootcamp\/learn\/lecture\/9478394#questions Errors are bound to happen &#8211; especially when someone else uses it in an unexpected way Error handling is used in an attempt to plan for these errors Example: Someone tries to write to a file only opened mode=&#8217;r&#8217; Without error handling, the entire ..<\/p>\n<div class=\"clear-fix\"><\/div>\n<p><a href=\"https:\/\/wiki.thomasandsofia.com\/?p=1908\" title=\"read more...\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[44],"tags":[],"class_list":["post-1908","post","type-post","status-publish","format-standard","hentry","category-python-bootcamp-0-to-hero"],"_links":{"self":[{"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=\/wp\/v2\/posts\/1908","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1908"}],"version-history":[{"count":5,"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=\/wp\/v2\/posts\/1908\/revisions"}],"predecessor-version":[{"id":1913,"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=\/wp\/v2\/posts\/1908\/revisions\/1913"}],"wp:attachment":[{"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1908"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1908"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wiki.thomasandsofia.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1908"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}