Exception Handling

In this article you will learn how you will handle the exception to prevent your program getting crash by using try, except and finally statement. This will help to enhance the readability and clarity.

During writing the program we always think about their program logic and syntax but in spite of there being some program occurring due the exception and program will crash automatically and stop the program for further proceedings.

In this case we will use Python Built-in Exception to escape the program from crashing.

Here are some common built in Function in Python Programming along with errors, that cause them are listed below.

AssertionError It is raised when an assert statement fails.
AttributeError It is raised when an invalid attribute reference is made.
EOFError It is raised when input() reaches the end of a file unexpectedly.
FloatingPointError It is raised when Floating point error will be made.
GeneratorExit It is raised when a generator closed the coroutine.
ImportError It is raised when trouble to import the module was not found.
IndexError It is raised when sequence range is out of range.
KeyError It is raised when the value not found
KeyboardInterrupt It is raised when the program is fiercely closed by keyboard.
MemoryError Raised when programs run out of memory.
NameError This error is raised when Python tries to load an object which does not exist in stack..
NotImplementedError It is raised when they require derived classes to override the method.
OSError It is raised when problem found in system
OverflowError This error is raised when arithmetic operations exceed the limits of current Python runtime.
ReferenceError It is raised when a weak reference proxy is used to access an unnecessary data collected reference.
RuntimeError It is raised when there is no category of error is fall.
StopIteration It is raised by the next() further there is no function available for iterate.
SyntaxError It is raised when the syntax error occurs.
IndentationError It is raised when base class for syntax errors related to incorrect indentation.
TabError It is raised when using inconsistent of Space.
SystemError It is raised when gets system internal error.
SystemExit Exception is raised by the sys.exit() function
TypeError It is raised when the unappropial types come.
UnboundLocalError It is raised when the reference made local methods.
UnicodeError It is raised when encode ,encoding and decoding error occurs.
UnicodeEncodeError It is raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.
UnicodeDecodeError It is raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError.
UnicodeTranslateError It is raised when get error while translating.
ValueError It is raised when bringing value is different from actual required value.
ZeroDivisionError It is raised when any number is divided by the zero.

Keywords are used in exception handling ?

Try :

Suspecial code comes under this block.

Except:

This block has handle form the error

Finally :

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Lets understand by the program

Program:

a=int(input("Enter Number"))
b=int(input("Second Number"))
print("Division",a/b)
print("Addition",a+b)

In this program you will see that there is no logical and syntax mistakes

Output:

Enter Number56
Second Number55
Division 1.018181818181818
Addition 111

But you are put zero value in ”B”

Enter Number12
Second Number0
Traceback (most recent call last):
  File "C:/Users/laptop/AppData/Local/Programs/Python/Python38-32/cal.py", line 3, in 
	print("Division",a/b)
ZeroDivisionError: division by zero

Error – ZeroDivisionError(this is called exception) ,addition syntax was correct but output wasl not display due to program crash .

lets understand another example

If assign string value in both variable:-

Enter Number"INDIA"
Traceback (most recent call last):
  File "C:/Users/laptop/AppData/Local/Programs/Python/Python38-32/cal.py", line 1, in 
	a=int(input("Enter Number"))
ValueError: invalid literal for int() with base 10: '"INDIA"'

ValueError(this is exception)

Let’s use the same program using exception handling

a=int(input("Enter Number"))
b=int(input("Second Number"))
try:
       	print("Division",a/b)

except ValueError:
       	print("Value error")
except ZeroDivisionError:
       	print("Putting Value Zero")
print("Addition",a+b)

Output:

Enter Number44
Second Number0
Putting Value Zero
Addition 44

Program 2:

try:
    f=open("abc.txt","r")
except FileNotFoundError:
    print("Not Found")
else:
    print(f.read())
    f.close()
finally:
   print(“Hi am finally block Run all time”)   

When the file ‘abc.txt’ does not exist.

Output:

Not Found
Hi am finally block Run all time

When the file ‘abc.txt’ exists.

Output:

India Is a great Country
Hi am finally block Run all time
Subscribe Now