error-in-python

Error Handing In Python

Exception Handing In Python

We can check for Exceptions using Try and Except method. But before that at the beginning of the book I had said that I will explain SyntaxError and other Errors in detail, here is the major Error which we encounter very often:

  • SyntaxError
  • NameError
  • ValueError
  • TypeError
  • IndexError

1. Syntax Error

You get syntax SyntaxError when you don’t follow rules and regulations provided by Python. Major exampled missing of parenthesis, missing of clone, Invalid naming of variable, Spelling mistake for the keywords, and many more.

Examples of SyntaxError:

>>> 10 = 32
SyntaxError: cannot assign to literal
>>> print "Very good"
SyntaxError: Missing parentheses in call to 'print'.
>>>if (a>b) #missing colon
File "<stdin>", line 1
if (a>b)
^
SyntaxError: invalid syntax
>>> ife(20>10):
SyntaxError: invalid syntax

2. Name Error

You get NameError when you try to use a variable or a function name that is not valid. This means that if Python encounters a name that it doesn’t recognize, you’ll probably get this error. Some common causes are: Misspelling the name of a built-in function, Forgetting to give a value to a variable before using it in a different statement.

Examples of NameError:

>>> x+=1
NameError: name 'x' is not defined
>>>name=(manhwa)
NameError: name 'manhwa' is not defined

>>>print(hello)
NameError: name 'hello' is not defined

prin("Python is easy to learn")
NameError: name 'prin' is not defined

3. Value Error

You get ValueError when a value is not the expected type.

Examples of ValueError:

>>>x=int("I will become Pirate King")
ValueError: invalid literal for int() with base 10: 'I will become Pirate King'

>>> z=[1,3,5,7,9]
>>> x,y = z
ValueError: too many values to unpack (expected 2)

>>>points=float("int")
ValueError: could not convert string to float: 'int'

4. Type Error

You get TypeError when an operation is performed on an inappropriate object type.

Examples of TypeError:

>>> a=input(‘Enter a number:’)
>>> b=a+10
>>> print(“10 more is {}”.format(y))
TypeError: can only concatenate str (not "int") to str

>>> x=5
>>> y=”123”
>>> print(x+y)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

5. Index Error

You get IndexError when your code tries to access an Index value that is not valid. This usually happens because the index is out of bounds due to being too large.

Examples of IndexError:

>>>s=[1,2,4,6,8}
>>>print(s[5])
IndexError: list index out of range

>>>name=[“Itachi”, “Naruto”, “Madara”, “Sasuke”, “Luffy”]
>>>name.pop(6)
IndexError: pop index out of range

Try And Except

We know of errors now. Suppose you want your program to run error-free, well of course everyone wants that. But you need your program to run even if there is an error, is there any possibility? Yes, there is. Python provides Try and except, using this you can show the user the message when a certain error occurs, so the user gets feedback where he went wrong. Giving feedback for your program is very important. I hope even I do get some feedback about this article, I will be waiting for your feedback. Back to Try and Except again, here you will require the knowledge of Error, that’s the reason why we covered Error before starting it.

manga = "Vagabond"
try:
    print(manhwa)
except:
    print("Name Error occurred")
Output: Name Error occurred
try:
    print(manhwa)
except NameError as error:
    print("This is what happened:",error)
Output: This is what happened: name 'manhwa' is not defined

Now, suppose you have declared a variable of name x and print y, you will get into NameError. What try and except does here is, you will execute your code inside try block, and if in case you run into some error

try:
    print(manga)
except:
    print("This is what happened:",error)
Output: Vagabond
number = 100
episode = 24
try:
    print(episode-4)
    print(episode/0)
except ZeroDivisionError as error:
    print("This error happened because:",error)

Output:

20
This error happened because: division by zero

We have added the error name ZeroDivisionError in except block, if you don’t know what error you are dealing with then you can mention except Exception as e and deal with the problem.

Finally

Finally is an add-on option that comes in handy with Try and except method. The statement inside finally will be executed, every time you use to try and except.

try:
    print(episode/0)
except ZeroDivisionError as error:
    print("This happened:",error)
finally:
    print("We have reached the end of the code")
Output:
This happened: division by zero
We have reached the end of the code
try:
    pass
except:
    print("Somethings not Good")
finally:
    print("I will be executed no matter what")
Output:
I will be executed no matter what

Deal With KeyError Using Try And Except

In Dictionary we had taken the example of CEO, lets consider that example again but with try and except method.

ceo = {"Google":"Sundar Pichai", 
       "Microsoft":"Satya Nadella",
       "Adobe":"Shantanu Narayen",
       "Tesla":"Elon Musk",
       "Apple":"Tim Cook",
       "Facebook":"Mark Zuckerberg"}
print(ceo["Google"])
print(ceo["Tesla"])
print(ceo["Amazon"])
Output:
Sundar Pichai
Elon Musk
KeyError: 'Amazon'

We get a KeyError because we haven’t declared the Amazon name yet. Now add a new key entry for Amazon and also add the Try and Except method so that the user gets the feedback on what he should do if he gets into some error.

try:
    ceo = {"Google":"Sundar Pichai", 
           "Microsoft":"Satya Nadella",
           "Adobe":"Shantanu Narayen",
           "Tesla":"Elon Musk",
           "Apple":"Tim Cook",
           "Facebook":"Mark Zuckerberg"}
    ceo['Amazon'] = "Andy Jassy"
    print(ceo["PayTM"])
    print(ceo["Google"])
except KeyError as k:
    print("This key is not found in the dictionary",k)
Output:
This key is not found in the dictionary 'PayTM'

Try and except is the best way to deal with the error. And with this you can generate your own message every time you run into an error, this enables you to understand the code in a better way.

How To Deal With FileNotFoundError?

We discussed FileNotFoundError in the previous article, and we will deal with it using Exception Handling. This is no big task to you, isn’t it? You are supposed to follow the same steps we followed in the rest of the Exception handling programs.

try:
    with open("unknownfile.txt") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("Oops! No File Found, Check Folder of the file and Try Again:)")
Output:
Oops! No File Found, Check Folder of the file and Try Again:)

We have a good error message for displaying File not Found.

Raise Exception

So far in try and except, whenever we encountered an error a normal message was executed. But what if you need to generate an error in addition to a meaning message. Raise keyword does that job by returning an error with the message we provide in except block.

try:
    a = int(input("Enter the a value:"))
    b = int(input('Enter the b value:'))
    result = a/b
    print(result)
except ValueError:
    #first method to raise an exception by mentioning error name in except :
    raise "Enter a valid number"
except:
    #second method to raise an exception without mentioning name in except:
    raise ZeroDivisionError("Enter non zero number for b")
Output:

Enter the a value:a
Traceback (most recent call last):
  File "/home/pythonbook/s.py", line 2, in <module>
    a = int(input("Enter the a value:"))
ValueError: invalid literal for int() with base 10: 'a'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pythonbook/s.py", line 7, in <module>
    raise "Enter a valid number"
TypeError: exceptions must derive from BaseException

Using Raise we can raise a new error with our own message.

Enter the a value:2
Enter the b value:0
Traceback (most recent call last):
  File "/home/pythonbook/s.py", line 11, in <module>
    raise ZeroDivisionError("Enter non zero number for b")
ZeroDivisionError: Enter non zero number for b

Conclusion

You can try 30 Days Python Programming by solving amazing code daily. Anime Vyuh Github Organization has a public repo, which will help you with 30 Days Of Python.

Check Out The Previous Tutorials Part On Learn Python.

If you like our content, support us by Buying a Coffee.

Subscribe to Anime Vyuh Newsletter.