|
| 1 | +#Exception handling using python |
| 2 | + |
| 3 | + |
| 4 | +a = 12 |
| 5 | +b = 0 |
| 6 | +#a = int(input()) |
| 7 | +#b = int(input()) |
| 8 | + |
| 9 | +try: |
| 10 | + c = a/b |
| 11 | + print(c) |
| 12 | + #trying to print an unknown variable d |
| 13 | + print(d) |
| 14 | + |
| 15 | +except ZeroDivisionError: |
| 16 | + print("Invalid input. Divisor cannot be zero.") |
| 17 | + |
| 18 | +except NameError: |
| 19 | + print('Name of variable not defined.') |
| 20 | + |
| 21 | + |
| 22 | +#finally statement is always executed whether or not any errors occur |
| 23 | +a = 5 |
| 24 | +b = 0 |
| 25 | +#a = int(input()) |
| 26 | +#b = int(input()) |
| 27 | + |
| 28 | +try: |
| 29 | + c = a/b |
| 30 | + print(c) |
| 31 | + |
| 32 | +except ZeroDivisionError: |
| 33 | + print("Invalid input. Divisor cannot be zero.") |
| 34 | + |
| 35 | +finally: |
| 36 | + print('Hope all errors were resolved!!') |
| 37 | + |
| 38 | + |
| 39 | +#A few other common errors |
| 40 | +#SyntaxError |
| 41 | + |
| 42 | +try: |
| 43 | + #eval is a built-in-function used in python, eval function parses the expression argument and evaluates it as a python expression. |
| 44 | + eval('x === x') |
| 45 | + |
| 46 | +except SyntaxError: |
| 47 | + print('Please check your syntax.') |
| 48 | + |
| 49 | + |
| 50 | +#TypeError |
| 51 | + |
| 52 | +try: |
| 53 | + a = '2' + 2 |
| 54 | + |
| 55 | +except TypeError: |
| 56 | + print('int type cannot be added to str type.') |
| 57 | + |
| 58 | + |
| 59 | +#ValueError |
| 60 | + |
| 61 | +try: |
| 62 | + a = int('abc') |
| 63 | + |
| 64 | +except ValueError: |
| 65 | + print('Enter a valid integer literal.') |
| 66 | + |
| 67 | + |
| 68 | +#IndexError |
| 69 | + |
| 70 | +l = [1,2,3,4] |
| 71 | + |
| 72 | +try: |
| 73 | + print(l[4]) |
| 74 | + |
| 75 | +except IndexError: |
| 76 | + print('Index of the sequence is out of range. Indexing in python starts from 0.') |
| 77 | + |
| 78 | + |
| 79 | +#FileNotFoundError |
| 80 | + |
| 81 | +f = open('aaa.txt','w') #File aaa.txt created |
| 82 | +f.close() |
| 83 | + |
| 84 | +try: |
| 85 | + #Instead of aaa.txt lets try opening abc.txt |
| 86 | + f = open('abc.txt','r') |
| 87 | + |
| 88 | +except FileNotFoundError: |
| 89 | + print('Incorrect file name used') |
| 90 | + |
| 91 | +finally: |
| 92 | + f.close() |
| 93 | + |
| 94 | + |
| 95 | +#Handling multiple errors in general |
| 96 | + |
| 97 | +try: |
| 98 | + a = 12/0 |
| 99 | + b = '2' + 2 |
| 100 | + c = int('abc') |
| 101 | + eval('x===x') |
| 102 | + |
| 103 | +except: |
| 104 | + pass |
| 105 | + |
| 106 | +finally: |
| 107 | + print('Handled multiples errors at one go with no need of knowing names of the errors.') |
| 108 | + |
| 109 | + |
| 110 | +#Creating your own Error |
| 111 | + |
| 112 | +a = 8 |
| 113 | +#a = int(input()) |
| 114 | + |
| 115 | +if a < 18: |
| 116 | + raise Exception('You are legally underage!!!') |
| 117 | + |
| 118 | +else: |
| 119 | + print('All is well, go ahead!!') |
0 commit comments