Exception Handling in Python

Exception Handling in Python



EXCEPTION : 


    Even when Program is syntactically correct , it may still cause an error when executed. These errors  occurs during run-time , known as EXCEPTION  .An exception is an event ,which occur during the execution of a program and disturbs the standard flow of execution. when a compiler runs into a situation which cannot handle , it raises an exception . 

Python have different types of errors.

Exception Handling in Python

Compile type Error (Syntax Error): 
Syntax error occurs when users Violate rules of Python language and these errors are very common types of errors while learning a new language . 
  
Logical Error : This type of error usually occurs when the program runs , but we got the wrong output. Logical errors may occur due to wrong algorithms or logic to solve a particular problem. 
 
Run time error : Name itself suggests that this error occurs while running a program, the reason behind it is " Wrong input from user "  .



Basically the first two types of errors are easy to deal with , we can find them and correct them. but when it comes to run-time error ,it's not in our hand , but as a good programmer we should be able to deal with it .Python provides some special syntax and keywords to deal with Run-time errors (exceptions).

Example : 

Program to illustrate use of try ,exception and finally keywords in Exception handling :



try:

   a= int(input("Enter first number "))

   b=int(input("Enter second one "))

   c=a/b

   print("Division is ",c)

except ValueError:

   print("invalid input....Program is terminating ")

except ZeroDivisionError:

   print("invalid input....Program is terminating ")

except KeyboardInterrupt:

   print("invalid input....Program is terminating ")

finally:

   print("Thank you")


Exception Handling in Python

In the above program  we had to use try , except and finally keyword .
try  keyword means we are not sure whether this code will run or not so compiler please check for it if code will run without any run time error then except exception block will not get execute but if there is an run-time error then it will go to exception block ,In above program we have mention exceptions like KeyboardInterrupt ,ZeroDivisionError, ValueError but if we don't know which type of run-time error will come then we can used "except exception:". exceptions can handle every type of error .
finally block will execute irrespective whether code will run or not . This block always execute even when there is run-time error


NOTE

The except block without an exception can also be used to print an error message and then re-raised exception



MULTIPLE EXCEPTION IN SINGLE BLOCK :


AN except clause may name multiple exceptions, so whatever exception is raised ,out of three exception specified, the name except block will execute

EXAMPLE :


try:

   a= int(input("Enter first number "))

   b=int(input("Enter second one "))

   c=a/b

   print("Division is ",c)

except( ValueError, ZeroDivisionErro,KeyboardInterrupt):

   print("invalid input....Program is terminating ")

finally:

   print("Thank you")




Python Raise :

Raising Exceptions intentionally is Possible in Python with the help of " raise " keyword. The syntax for raise statement is

raise [Exception [,args [,traceback]]]


Here, Exception is the name of an exception to be raised (TypeError) .args is optional and specifies a value for the exception argument .Default value of args  is None .
Example :

try: 

  x=5

  print(x)

  raise ValueError 


except:

  print(“exception occurred”)


OUTPUT :

 10

 Exception occurred 


In the above example there is no error .We had declared a variable and just printed it. But we have intentionally raised an exception .



NOTE

Without mentioning any specific exception is not a good programming practice because it catches all exceptions, and the programmer is not able to identify the exact error .



List of built in Exception :

As a good programmer we should have knowledge different exceptions in Python

Exception 

Description 

Exception 

Base class for all exception

StopIteration

Generated when next() method not point to an object

StandardError

Base class for all built-in exception

ArithmaticError

Error generated due to Mathematical calculations 

OverflowError

Raise when maximum value get exceeds 

FloatingPointError

Raise when floating point calculation could not Perform 

ZeroDivisionError

Raised when a number gets divided by zero

ImportError

Raised when import statement fails 

KewboardInterrupt

Raise when when user Interrupts program execution

LookupError

Base class for all lookup errors 

IndexError

Raised when index is not found

KeyError

Raised when key is not found

NameError

Raised when identifier is not found