|
| 1 | +# Description: In the break_me.py file write four simple Python functions: |
| 2 | +# Each function, when called, should cause an exception to happen |
| 3 | +# Each function should result in one of the four most common exceptions you’ll find. |
| 4 | +# for review: NameError, TypeError, SyntaxError, AttributeError |
| 5 | +# Comment: Execute this script in Python3.6 |
| 6 | +# Last modified: 10/07/2017 - davidkan@ |
| 7 | + |
| 8 | + |
| 9 | +class PracticeExceptions: |
| 10 | + |
| 11 | + def __init__(self): |
| 12 | + """ |
| 13 | + Creates a constructor when the instance is initialized |
| 14 | + """ |
| 15 | + self.python = 'python' |
| 16 | + self.java = 'java' |
| 17 | + self.c_sharp = 'c#' |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def SyntaxErrorExample(): |
| 21 | + """ |
| 22 | + Function will demo a SyntaxError exception |
| 23 | + :return: None |
| 24 | + """ |
| 25 | + a = 1 |
| 26 | + b = 'b' |
| 27 | + try: |
| 28 | + eval("1 + a") |
| 29 | + eval("1 === b") |
| 30 | + except SyntaxError as s: |
| 31 | + print("That won't work. Try again") |
| 32 | + print(s) |
| 33 | + |
| 34 | + def AttributeErrorExample(self): |
| 35 | + """ |
| 36 | + Function will demo an AttributeError exception |
| 37 | + :return: None |
| 38 | + """ |
| 39 | + try: |
| 40 | + print(self.python) |
| 41 | + print(self.java) |
| 42 | + print(self.c_sharp) |
| 43 | + print(self.sql) |
| 44 | + except AttributeError as a: |
| 45 | + print("This does not exist. Try again.") |
| 46 | + print(a) |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + def TypeErrorExample(): |
| 50 | + """ |
| 51 | + Function will demo a TypeError exception |
| 52 | + :param self: |
| 53 | + :return: None |
| 54 | + """ |
| 55 | + a = 1 |
| 56 | + b = 'b' |
| 57 | + try: |
| 58 | + eval("1 + a") |
| 59 | + eval("1 + b") |
| 60 | + except TypeError as t: |
| 61 | + print("That won't work. Try again") |
| 62 | + print(t) |
| 63 | + |
| 64 | + @staticmethod |
| 65 | + def NameErrorExample(): |
| 66 | + """ |
| 67 | + Function will demo a NameError exception |
| 68 | + :return: None |
| 69 | + """ |
| 70 | + # Declare a variable and assign it a string |
| 71 | + school = "University of Washington" |
| 72 | + |
| 73 | + try: |
| 74 | + if school: |
| 75 | + print(schools) |
| 76 | + except NameError as n: |
| 77 | + print("The varable does not exist. Try again") |
| 78 | + print(n) |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + """ |
| 83 | + Create an instance of the class and call all four functions |
| 84 | + """ |
| 85 | + # Create an instance |
| 86 | + common_errors = PracticeExceptions() |
| 87 | + |
| 88 | + # Call the functions |
| 89 | + common_errors.NameErrorExample() |
| 90 | + common_errors.TypeErrorExample() |
| 91 | + common_errors.SyntaxErrorExample() |
| 92 | + common_errors.AttributeErrorExample() |
| 93 | + |
| 94 | + |
0 commit comments