Section 10: Errors and Exception Handling

  Python Bootcamp 0 to Hero

< Section 9 | Section 11

Errors and Exception Handling

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478394#questions

  • Errors are bound to happen – 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=’r’
    • Without error handling, the entire script would stop.
    • Error handling allows the script to continue even if there is an error.
      • it also reports the error

try, except, and finally

  • try: This is a block of code to be attempted (that may lead to an error)
  • except: Block of code will execute in case there is an error in the try block
  • finally: A block of code to be executed regardless of an error.
def add(n1, n2):
    return n1 + n2
n1=20
n2=input("Enter a number: ")
print("sum of {} and {} is "+add(n1,n2))

Enter a number: 10
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Using Error handling

def add(n1, n2):
    try:
        result = n1 + n2
    except:
        # somefunction log error
        return False
    else:
        # only runs when not an error
        return result
n1=20
n2=input("Enter a number: ")
print("sum of {} and {} is {}".format(n1, n2, add(n1,n2)))

Enter a number: 10
sum of 20 and 10 is False

Using finally

I don’t see how this is different than just adding a line of code under the try/except block…

try:
   f=open('testfile','r')
   f.write('write a test line')
except OSError:
    print("OS Error!")
except TypeError:
    # not going to happen, just an example
    pass
except:
    # all non-explicit exceptions
    pass
finally:
    print("I always run.")

OS Error!
I always run.

Full Example

def ask4int():
    while 1:
        try:
            result = int(input("Please enter a number: "))
        except:
            print("Whoops! That was not a number!")
            continue
        else:
            print("Thank you!")
            break
        finally:
            print("End of try/except/finally")
            print("I will ALWAYS run at the end!")
ask4int()

Please enter a number: a
Whoops! That was not a number!
End of try/except/finally
I will ALWAYS run at the end!
Please enter a number: 2
Thank you!
End of try/except/finally
I will ALWAYS run at the end!

Errors and Exceptions Homework

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478396#questions

 

Errors and Exceptions Solutions

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478404#questions

 

Pylint Overview

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478414#questions

There are several testing tools.  We will focus on two:

  • pylint
    • This is a library that looks at your code and reports back possible issues and provides a score (10/10 is the best)
    • This is usually used with larger organizations with various teams of developers to ensure coding standards are met.
  • unittest
    • This is a built-in library that will allow you to test your programs and check you are getting the desired outputs

Pylint checks for code errors and styling (PEP 8)

Install Pylint

Use the command line and text editor for these examples

CMD: pip install pylint

Simple1.py

a = 1
b = 2
print(a)
print(B)
CMD: pylint simple1.py

************* Module simple1
simple1.py:4:0: C0304: Final newline missing (missing-final-newline)
simple1.py:1:0: C0111: Missing module docstring (missing-docstring)
simple1.py:1:0: C0103: Constant name “a” doesn’t conform to UPPER_CASE naming style (invalid-name)
simple1.py:2:0: C0103: Constant name “b” doesn’t conform to UPPER_CASE naming style (invalid-name)
simple1.py:4:6: E0602: Undefined variable ‘B’ (undefined-variable)

————————————-
Your code has been rated at -12.50/10

'''
A very simple script
'''
def func():
    '''
    my simple function
    '''
    first = 1
    second = 2
    print(first)
    print(second)
func()
CMD: pylint simple1.py

———————————————————————
Your code has been rated at 8.33/10 (previous run: 10/10, +22.5)

Running tests with the Unittest Library

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478416#questions

Create 2 files

  • caps.py
  • test_caps.py

Failure test

caps.py

def cap_text(text):
    '''
    returns the capitalized version of a string.
    '''
    return text.capitalize()

test_caps.py

import unittest
import caps

class TestCap(unittest.TestCase):
    def test_one_word(self):
        text = 'python'
        result = caps.cap_text(text)
        self.assertEqual(result, 'Python')
    def test_one_word(self):
        text = 'monte python'
        result = caps.cap_text(text)
        self.assertEqual(result, 'Monte Python')

if __name__ == '__main__':
    unittest.main()
CMD: python test_caps.py

F
======================================================================
FAIL: test_one_word (__main__.TestCap)
———————————————————————-
Traceback (most recent call last):
File “test_caps.py”, line 12, in test_one_word
self.assertEqual(result, ‘Monte Python’)
AssertionError: ‘Monte python’ != ‘Monte Python’
– Monte python
? ^
+ Monte Python
? ^

———————————————————————-
Ran 1 test in 0.002s

FAILED (failures=1)

Failure resolved

caps.py

def cap_text(text):
    '''
    returns the capitalized version of a string.
    '''
    return text.title()
CMD: python test_caps.py

.
———————————————————————-
Ran 1 test in 0.002s

OK
 

LEAVE A COMMENT