Errors And Exception Handling in python

An unavoidable part of being a programmer is that your programs are going to give a lot of errors. You can’t avoid bugs

You can’t avoid programs breaking a simple print function here with let’s say a misspelt word with let’s

say no comma. If I run this

We’ve been seeing this a lot right.

that crashes our program like this is called an exception and Python raises these exceptions whenever

the interpreter says hey I have no idea what you’re doing.

Something’s wrong.

I don’t know what I’m doing anymore.

I’m going to stop whatever I’m doing and I’m going to give you an output.

This is bad because right now we’re just playing.

But if we’re Google and people depend on us to maybe check their email to watch YouTube videos if our

programs have exceptions and they stop working and they error out that’s bad.

That could cost companies millions.

So how can we handle these exceptions that crash our program.

Well we need something called error handling.

It’s a natural part of being a programmer and a great programmer is able to handle errors in their program

because instead of letting our programs just error we’re able to handle them so that if we get something

like a type error like this we can actually handle that error within our programs.

And in this section we’re going to learn all about them.

But the key takeaway is that error handling allows us to let the python script continue running even

if there are errors.

Sounds pretty interesting right. Well before we get into that let’s just talk about some of the errors that exist in Python

Errors and Exceptions

Syntax Error:

Syntax occurs when we have violate the rules of python and they are most kind of error that we get.Consider ex. Below

def hello()
    return True
  File "<ipython-input-2-20fd68509224>", line 1
    def hello()
               ^
SyntaxError: invalid syntax

In this formationed code, we have missed the “ : “ after function hello() .

Try : Can you Fix now ?

i=0
if i==0 print(i)
  File "<ipython-input-3-a2e2be63c84d>", line 2
    if i==0 print(i)
            ^
SyntaxError: invalid syntax

Logical Error:

Logical error may occurs, specifies all those type of errors in which the program executes but gives incorrect results. In this case logic error leads to a run-time error that causes the program to terminate abruptly. These types of run time error are known as exceptions.

Examples:

li=[1,2,3]
print(li[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-0b476ae561e0> in <module>
      1 li=[1,2,3]
----> 2 print(li[4])

IndexError: list index out of range

This happened because are trying to access the item of list li where index of the item is outside the bounds of the list.

Lets Exercise

Question 1: What would the following code generate?

mydict = ["name":"kuldeep", "surname":"chauhan"] 
print(mydict) 
a)A type Error  b) A Syntax Error  c) ["name":"kuldeep", "surname":"chauhan"]

Ans: A SyntaxError would be generated because when you start with square brackets Python thinks you are about to define a list, but then you use colons instead of commas so that is not the correct syntax to define a list, thus the SyntaxError.

Question 2: Here’s one more challenge. What would the code generate this time?

a = [1, 2, 3}
a)A SyantaxError  b)A TypeError  c)A NameError

Ans  : Again you would get a SyntaxError because Python thinks you are about to define a list since you start with square brackets but then you close the array with a curly brackets which does not follow the Python syntax rules.

Question 3:What would the below code output?

print(kuldeep) 
a)SytanxError
 b)NameError

Ans :
Good job!
You would get a NameError because variable name kuldeep was not defined in the code. Don’t confuse variable names with strings. Strings have quotes, variable names don’t.

Question 4: What would you get this time?

mylist = [kuldeep, singh, chauhan] 
print(mylist) 
a)	[kuldeep, singh, chauhan] 
b)	A SyntaxError
c)	A NameError
d)	A typeError

Ans
Good job!
You would get a NameError again because kuldeep, singh, and chauhan names were not defined in the script. So, as soon as Python detects that kuldeep was not defined, it interrupts the code with a NameError and it doesn’t even check the rest of the code. You would get a NameError again because kuldeep, singh, and chauhan names were not defined in the script. So, as soon as Python detects that kuldeep was not defined, it interrupts the code with a NameError and it doesn’t even check the rest of the code.

Exceptions in python:

Exceptions is an event ,which occurs during the execution of a program and disrupts normal flow of the program’s execution. When program rises an exception it must handle the exception or the program will be immediately terminated.
Example

5/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-10-0106664d39e8> in <module>
----> 1 5/0

ZeroDivisionError: division by zero

Handling Exceptions:

try:
	Statements

except:
	statements

Step 1: First the try block will be executed
Step 2: a) if no exception occurs, the except block skipped
b) if exception occurs, the matched except block will executed

#Program to handle divide by zero exception
num=int(input("Enter the numerator"))
deno=int(input("Enter the denominator"))
try:
    quo=num/deno
    print("Quotient: ",quo)
except ZeroDivisionError:
    print("Denominator can't be zero")

Output
Enter the numerator10
Enter the denominator0
Denominator can’t be zero

Multiple Except Block

try:
    num=int(input("Enter the number"))
    print(num**2)
except(KeyboardInterrupt):
    print("You should have enter the number......program terminated.....")
except(ValueError):
    print("Please check before you enter......program terminated.....")
Enter the number-1

Finally block

Finally block is always executed before leaving the try block. This means finally block are always executed whether an exception has occurred or not.

try:
    print("Raising Exception")
    raise ValueError

finally:
    print("Performing clean up in finally block")
Raising Exception
Performing clean up in finally block
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-19941b70379b> in <module>
      1 try:
      2     print("Raising Exception")
----> 3     raise ValueError
      4 
      5 finally:
ValueError: 

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top