Social Media

2/10/2019

try, except and finally

In try block we have to write that code of our program, where we expecting that exception will come.

Some points about try and except:
  • We cannot have any except block without try block.
  • In except we have to catch the object thrown by that line which is present in the try block.
  • There can be more than one except block for a single try block.
  • except block only executed when any exception occurs, if no exception occurs program will execute normally and don't enter in the except block.
  •  If we have not made any except block, then python will handle exception automatically.
  • We can also accept more than one exception in the except by writing the name of the class separated by the ",". 
Some points about finally block:
  • This block always be executed, it doesn't matter whether the exception is occurred or not in our program.
  • finally always come after the except block.
  • finally works before the default exception catch mechanism of python.
  • try block should have at least one except or finally block.
  • We can't made more than one finally block.
  • If we made except by ourselves and exception occurs, then in this case, first except block will be executed and then finally block executed.
Note* We can also use else block with try block. else block will execute when there is no exception occurs in our program.
We have to write the else block before finally block and after except block.


try:


   """ write your code here""" 

except ExceptionClassName1: 

   """Write your code here""" 


except ExceptionClassName2: 

   """Write your code here" 

else:   

   """Write your code here"""

finally:

    """Write your code here"""
Be First to Post Comment !
Post a Comment