|
| 1 | +""" |
| 2 | +Suppose you want your program to run error free, well everyone wants that. |
| 3 | +But what if we need our program to run even if there is an error, is there any possibility? Yes There sure is. |
| 4 | +Python provides Try and except, using this you can show user the message when certain error is occurred we call it exception. |
| 5 | +User get the feedback where he went wrong, using Try And Except Technique. |
| 6 | +Giving feedback for your program is every important. |
| 7 | +I hope even I do get some feedback about this 30DaysOfPython, I will be waiting for your feedback. |
| 8 | +Back to Try and Except again, here you will require the knowledge of some common errors |
| 9 | +""" |
| 10 | +#example 1 |
| 11 | + |
| 12 | +try: |
| 13 | + a = int(input("Enter a number: ")) #integer inputs required |
| 14 | + b = int(input("Enter a number2: ")) |
| 15 | + div = a/b |
| 16 | + if a>b: |
| 17 | + print("{} is greater than {}. Quotient is:{}".format(a,b,div)) |
| 18 | + else: |
| 19 | + print("{} is greater than {}. Quotient is:{}".format(b,a,div)) |
| 20 | + |
| 21 | +except ValueError as e: |
| 22 | + #this except block is printed when user enters a string instead of integer |
| 23 | + print("This Occured:",e) |
| 24 | +except ZeroDivisionError as e: |
| 25 | + #this except block is printed when user inputs 0 to number 2, b |
| 26 | + print("This occured:",e) |
| 27 | + |
| 28 | +#example 2 |
| 29 | +try: |
| 30 | + ceo = {"Google":"Sundar Pichai", |
| 31 | + "Microsoft":"Satya Nadella", |
| 32 | + "Adobe":"Shantanu Narayen", |
| 33 | + "Tesla":"Elon Musk", |
| 34 | + "Apple":"Tim Cook", |
| 35 | + "Facebook":"Mark Zuckerberg"} |
| 36 | + |
| 37 | + ceo['Amazon'] = "Andy Jassy" |
| 38 | + |
| 39 | + print(ceo["PayTM"]) |
| 40 | + print(ceo["Google"]) |
| 41 | + print(ceo["Tesla"]) |
| 42 | + print(ceo["Amazon"]) |
| 43 | + print(ceo["Apple"]) |
| 44 | + |
| 45 | +except KeyError as k: |
| 46 | + #this except block is executed when invalid key is entered |
| 47 | + print("This key is not found in the dictionary",k) |
| 48 | +except Exception as e: |
| 49 | + print("Something went wrong",e) |
| 50 | + |
| 51 | +#example 3 |
| 52 | + |
| 53 | +try: |
| 54 | + with open("unknownfile.txt") as file: |
| 55 | + content = file.read() |
| 56 | + print(content) |
| 57 | +except FileNotFoundError: |
| 58 | + print("Oops! No File Found, Check Folder of the file and Try Again:)") |
0 commit comments