Finally Block in python

The finally keyword is used in a try...except blocks. It defines a block of code to run when the try...except...else block is final.

It is not recommended to place a cleanup code inside the try block because there is no guarantee for the execution of every statement inside the try block.

And also, it is not recommended to place a cleanup code>except block won't be executed.

We required someplace to define a cleanup code which executes irrespective of whether the exception raised or not raised and whether the exception is handled or not handled, the best place is nothing but a finally block.

The main purpose of the finally code is to maintain a cleanup code.

The Syntax is:

try:
    Risky code:
except:
       Handling code
finally:
      Cleanup code

Case 1: If No Exception

try:
    print("try")
except ZeroDivisionError:
    print("Except")
finally:
    print("finally")

If there is no exception then try and finally block will execute

if-there-is-no-exception-then-try-finally-blocks-will-execute

Case 2: If the exception raised and handled

try:
    print("try")
    print(10/0)
except ZeroDivisionError:
    print("Except")
finally:
    print("finally")

If an exception got raised and handled by exception block, then try, except and finally blocks got executed.

if-there-is-an-exception-then-try-except-finally-block-executes

Case 3:If exception raised but not handled

try:
    print("try")
    print(10/0)
except ValueError:
    print("Except")
finally:
    print("finally")

If the exception raised but not handled then first try and finally block will execute, and then zeroDivisionError will execute.

If-exception-raised-but-not-handled

Abstract Method in python

OS.__exit(0) vs Finally Block in python

There is only one situation where finally block won't be executed, i.e., whenever we are using OS._exit(0).

Whenever we are using the OS_exit(0), then the python virtual machine itself will be shut down and in this particular case finally block won't be executed.

OS._exit(0)

Here Zero represents the status Code.

Zero means normal termination.

Non-zero means abnormal termination

The python virtual machine internally uses this status code.

Whether it is zero or non zero, there is no difference in the result of the program.

The following example demonstrates the OS._exit(0)

import os
try:
    print("try")
    os._exit(0)
except ValueError:
    print("except")
finally:
    print("finally")

The output is:
try

Python Interfaces

Difference between Finally Block and Destructor

Finally Block Destructor
Finally block is meant for cleanup activities related to the try block, i.e., whatever the resources we opened as part of try block will be cleaned inside the finally block.

Destructor is meant for cleanup activities related to the object; whatever the resources related to the object should be deallocated inside the destructor which will be executed before destroying the object.

Control Flow in try-except-finally blocks

The following cases demonstrate the control flow in try-except-finally blocks

Case 1: If there is no exception

try:
    print(statement-1)
    print(statement-2)
    print(statement-3)
except:
    print(statement-4)
finally:
    print(statement-5)
print(statement-6)   

If there is no exception occur, then, try block will execute and finally block will also execute, excluding the except and then the remaining code will execute normally.

The output will be : statement-1,2,3,5,6 and normal termination

Case 2: If an exception raised at the statement-2 and corresponding except block matched, then the control automatically goes to except block and then finally block will execute, also remaining blocks will execute normally.

The output will be: statement-1,4,5,6 and normal termination.

Case 3:If an exception raised at the statement-2 and the corresponding except block not matched; then the finally block will execute, and the abnormal termination will happen.

The output will be: statement-1, normal termination.

Case 4: If an exception raised at the statement-4 if an exception raised at the exception block, then finally block will execute and the abnormal termination will happen.

The output will be: statement-5 and abnormal termination.

Case 5:If an exception raised at statements 5 or 6 then it is always abnormal termination.

Exception Handing in Python

Nested try-except-finally Blocks

We can take try-except-finally blocks inside the try or except or finally. Hence nesting of try-except-finally blocks is possible.

The general risky code we have to take inside the outer try block and too much risky code we have to take inside the inner try block.

Inside the inner try block if an exception is raised, then the inner except block is responsible to handle it; if it is unable to handle, then the outer except block is responsible to handle it.

The following example demonstrates the nested try-except-finally block

try:
    print("outer try block")
    try:
        print("Inner try block")
    except ZeroDivisionError:
        print("Inner except block")
    finally:
        print("Inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")        

There is no exception in the above program and hence the inner except and outer except block won't be executed, except that all the blocks will execute.

The output is:

nested-try-except-finally-block

If an exception is raised in the inner try block and the inner except block will match then the inner exception block, and inner finally block will execute.

And the exception is handled by the inner exception itself, and hence the outer exception block won't execute, but the outer finally block will execute.

try:
    print("outer try block")
    try:
        print("Inner try block")
        print(10/0)
    except ZeroDivisionError:
        print("Inner except block")
    finally:
        print("Inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")     

The output is:

nested-try-except-finally-block-an-exception-is-raised-in-the-inner-try-block

In the below example, an exception is raised in the inner try block but the corresponding except block not matched, and hence the inner finally block will execute and then the outer except block will execute and then the outer finally block.

try:
    print("outer try block")
    try:
        print("Inner try block")
        print(10/0)
    except ValueError:
        print("Inner except block")
    finally:
        print("Inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")   

The output is:

nested-try-except-block-exception-is-raised-in-the-innertryblock%20-but-the-corresponding-exceptblock-notmatched

If an exception is raised in the outer try block, then the corresponding except block will be outer except block, and hence the outer except block and the outer finally block will be executed.

try:
    print("outer try block")
    print(10/0)
    try:
        print("Inner try block")
        
    except ValueError:
        print("Inner except block")
    finally:
        print("Inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")   

The output is:

nested-try-except-finaly-if-an-exception-raised-in-the-outer-try-block

Python Polymorphism

else Block with try-except-finally in python's exception Handling

if-else==>if condition is false then only else will be executed
for-else==>If loop executed without a break, then only else block will execute.
while-else==>if loop executed without a break then only else block will execute.

The following example demonstrates, if the condition is false, then only the else part will execute.

value=10
if value>10:
    print("value is greater than 10")
else:
    print("value is less than 10")

The output is:

else-block-execute-only-when-if-statement-fails

The following example demonstrates the loops with else block

for info in range(10):
    print("The Current Item:",info)
else:
    print("congratulations, all item processed successfully")

The output is:

loop-with-else

The following example demonstrates While executing a loop if the break statement is encountered, then the else part is not going to execute.

for info in range(10):
    if info>5:
        break
    print("The Current Item:",info)
else:
    print("congratulations, all item processed successfully")

The output is:

the-output-of-else-with-break-statement

If we use else block with try-except-finally, if there is no exception in a try block, then only the else block will execute

The Syntax is:

try:
    Risky code
except:
    Handling code
    will be executed if an exception inside try
else:
    will be executed if there is no exception inside try
finally:
    cleanup code
    will be executed whether exception raised or not raised and handled or not handled    


The following example demonstrates the; when there is no exception in the try block then else part will execute

try:
   print("try")
except:
       print("Except")
else:
     print("Else")
finally:
      print("Finally")

The output is:

else-block-execution-ehrn-there-is no-exception-in-the-try-block

The following example demonstrates the execution of else block with try-except-finally when an exception occurs in the try block then the else part will not execute.

try:
   print("try")
   print(10/0)
except:
       print("Except")
else:
     print("Else")
finally:
      print("Finally")

The output is:

else-block-with-try-except-finally

The following example demonstrates without except block the else part is not valid and the python will throw a syntax error

try:
   print("try")
else:
     print("Else")
finally:
      print("Finally")

The output is:

without-except-block-the-else-block-is-invalid

There is no chance of executing both except block and else simultaneously If we want to use the else block then compulsory the except block should be there

The following example demonstrates the else block with try-except-finally block

file=None
try:
    file=open("info.txt","r")
except:
    print("Some problem while locating and opening the file")
else:
     print("File opened successfully")
     print("The data present in the file is:")
     print("#",*30)
     print(file.read())
finally:
    if file is not None:
        file.close()

The output is: If the file is available in my system then

File opened successfully
The data present in the file is:
#############################
Line-1 of abc.txt file
Line-2 of abc.txt file
Line-3 of abc.txt file
Line-4 of abc.txt file
Line-5 of abc.txt file

The output is: If the file is not present in the system.

if-the-file-is-not-present-in-the-system

Python Special Characters

The Various Possible Combinations of try-except-else-finally Block

Whenever we are writing try block, compulsory we should write except or finally block, Because the try block without except or finally is invalid.

Whenever we are writing except block, compulsory try block should be there, because the except without try block is always invalid.

Whenever we are writing finally block compulsory try block should be there, because the finally block without try is always invalid.

Whenever we are writing else block compulsory except block should be there, because else without except is always invalid.

We can write multiple except blocks for the same try block with, but we cannot write various else block and finally block.

The try-except-else-finally order is important.

We can write try-except-else-finally block inside try-except-else-finally block

The following table explains the valid syntax for the try-except-else-finally block.

Syntax

Status

try:

print("try")

Invalid

except:

print("Hello")

Invalid

else:

print("Hello")

Invalid

finally:

print("Hello")

Invalid

try:

print("try")

except:

print("except")

Valid

try:

print("try")

finally:

print("finally")

Valid

try:

print("try")

except:

print("except")

else:

print("else")

Valid

try:

print("try")

else:

print("else")

Invalid

try:

print("try")

else:

print("else")

finally:

print("finally")

Invalid

try:

print("try")

except xxxx:

print("except-1")

except yyyy:

print("except-2")

Valid

try:

print("try")

except:

print("except-1")

else:

print("else")

else:

print("else")

Invalid

try:

print("try")

except:

print("except-1")

finally:

print("finally")

finally:

print("finally")

Invalid

try:

print("try")

print("Hello")

except:

Invalid

try:

print("try")

except:

print("except")

print("Hello")

finally:

print("finally")

Invalid

try:

print("try")

except:

print("except")

print("Hello")

else: print("else")

Invalid

try:

print("try")

except:

print("except")

try:

print("try")

except:

print("except")

Valid

try:

print("try")

except:

print("except")

try:

print("try")

finally:

print("finally")

Valid

try:

print("try")

except:

print("except")

if 10>20

print("if")

else:

print("esle")

Valid

try:

print("try")

try:

print("inner try")

except:

print("inner except block") finally:

print("inner finally block") except:

print("except")

Valid

try:

print("try")

except:

print("except")

try:

print("inner try")

except:

print("inner except block") finally:

print("inner finally block")

Valid

try:

print("try")

except:

print("except")

finally:

try:

print("inner try")

except:

print("inner except block") finally:

print("inner finally block")

Valid

try:

print("try")

except:

print("except")

try:

print("try")

else:

print("else")

Invalid

try:

print("try")

try:

print("inner try")

except:

print("except")

Invalid

try:

print("try")

else:

print("else")

except:

print("except")

finally:

print("finally")

Invalid

Python string Datatype

Types of Exceptions in python Exception Handling

There are two types of exceptions in python

  • Predefined Exceptions
  • User-Defined Exceptions

Predefined Exceptions:

The predefined exceptions will raise automatically by the python virtual machine whenever a particular event occurs.

The predefined exceptions are also known as inbuilt exceptions or PVM Exceptions.

Example 1: Whenever we are trying to perform a division by zero, automatically python will raise

ZeroDivisionError.

print(10/0)  #ZeroDivisionError

Example 2: Whenever we are trying to convert str type into int type and the string does not contain the int valve, then we will get ValueError Automatically.

data=int("Ten") ##ValueError

User-Defined Exceptions:

Sometimes we have to define and raise exceptions explicitly to indicate that something goes wrong, such types of exceptions are called User Defined Exceptions or Customized Exceptions. The user-defined exceptions are also known as Customized Exceptions or Programmatic Exceptions

The programmer is responsible to define these exceptions and Python not having any idea about these. Hence we have to raise explicitly based on our requirement by using the "raise" keyword.

Example:

InsufficientFundsException
InvalidPinException
TooYoungException
TooOldException

How to Define and Raise Customized Exceptions:

Every exception in python is a class and it should be a child class of BaseException.

Example:

class NameofException(PredefinedException):
     def __init__(self,msg):
           self.msg=msg

Example:

class TooYongException(Exception):
      def __init__(self,msg):
            self.msg=msg

The TooYoungException is our exception class name and it is the child class Exception, and we can raise an exception by using the raise keyword.

The Syntax is:

raise TooYoungException("Massage")

The following example demonstrates the customized exception

class TooYoungException(Exception):
    def __init__(self,msg):
        self.msg=msg
        
class TooOldException(Exception):
    def __init__(self,msg):
        self.msg=msg
        
age=int(input("Enter Age:"))
if age>60:
    raise TooYoungException("Please Wait some more time, definitely you will get best match")
elif age<18:
   raise TooOldException("you are crossed marriage age, no chance of getting marriage")
else:
    print("You will get match details soon by email...!!!")        

The output is: When the input is 99 then

the-output-when-the-input-is-99

The output is: When the input is 19

the-output-when-the-input%20is-19

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions