Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Exception handling in python
  5. Try- Finally clause

Try- Finally clause

Exception in a program as a situation that occurs during runtime and programmer has no control on it.

A good program is one that has a code that handles an exception well i.e., in case an exception occurs, then the exception handling code written for it, will take over and do the necessary action.

Exception handling in python involves the use of try-except-finally clauses wherein the code that may generate an exception is written in the try block and the code for handling the exception when the exception is raised, written in except block. Code written under finally clause will be executed no matter if the try block raises an error or not.

Finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.


   #some code
   #Handling exception
   #always executed code.


    print("result of 10/5=", (10/5))
    print("result of 10/0=", (10/0))
    print("Denominator must not be zero.")
    print("This block is always executed.")
result of 10/5= 2.0
Denominator must not be zero.
This block is always executed.

This is all about try-except-finally clause in python.

Was this article helpful to you? Yes No

How can we help?