Exception Handling in Python

Exception Basics

Exception  : Nothing but an event that are modify the flow of event or a flow of control in a program . In python or any other languages Exception are triggered automatically on error . In this we will see four statement that are used in handling a Exception  in a program.

1st is try/except  (catch  and recover from exception occur in python code)

2nd is try/finally (Cleanup action whether exception i occur or not)

3rd is raise (triggered an exception manually)

4th is assert ( conditionally triggered an exception)

5th is with/as (with message)

In Python Exception Handling is very important topic because it use many time when work on large program or a project.Python raise an exception when it detect error at runtime in a program.If you can catch  the error or handle  this error in your code or ignore the exception that raise . If you ignore the error in python code ,Python default exception-handling will execute , it stop the current running code and print an error message.

A code try statement to catch and recover from Exception Python will jump try statement when error is detect and your program will execute resume after try. Sometime a condition may occur so rarely that harder to justify to handle it .so you can eliminate special -case code by handling  unusual case in Exception handling .

Default Exception HandlerThe simple example i have take to show to the Default exception works on Python . The first line  of the code id  def fetcher(obj , index)  it is a function that are return the obj[index], it nothing but a x[3] we can define in python terminal. If we tries  to increase the range of index i.e 4 but x is 3 so Python detect error and Default Exception Handler will execute and print message string index out of range. 

 

lets we handle the above error through try/except

Exception Handle use try/except statement

 

The above code is edit in vi editor .In above code firstly define a function called fetcher and this function return the value i.e x[4].

x is an variable contain a string ‘span’ the handle a exception  in try block we use exception statement if exception is occur the except statement will automatically execute  and print the message  ‘Error occur’ .

 

Exception Handle use try/except