October 11

Exception Handling

You need to handle exception in your programme otherwise it will terminate after exception (error).
If you have any code which may cause error while execution, you need to put that code under “try” block, after the try: block, you need to include an except: block.
You can write exception handling in following ways :

  • try… except…
  • try… except… else..
  • try… except… finally…
  • Try block will start executing, if there will any error while file handling then it will go to except block else it will not go to except block.

    We can write above programme in more relevant using try… except.. else.. block.
    Else block executes only when there is no error in try block.

    We can write same programme using finally block also, if there is any error while writing into the file.
    finally block will always execute, doesn’t matter whether error occurred in try block or not.