×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python finally Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

The finally is a keyword (case-sensitive) in python, it is a part of "try...except...finally" block, it is used to define a block (of coding statements) to execute finally i.e. no matter there is an exception or not in the "try" block. The finally block executes in any case.

Syntax

Syntax of finally keyword:

try:
  statement(s)-1
except:
  statement(s)-2
finally:
  statement(s)-3

While executing the statement(s)-1, if there is any exception raises, control jumps to except block and statement(s)-2 executes, in case of finally block – no matter there is an exception in try block or not, statement(s)-3 executes in any case.

Sample Input/Output

Input:
a = 10
b = 0

try:
  # no error
  result = a%b
  print(result)
    
except:
  print("There is an error")
finally:
  print("Finally block, Bye Bye")

Output:
There is an error
Finally block, Bye Bye

Example 1

Find modulus of two number and handle exception, if divisor is 0.

# python code to demonstrate example of 
# try, except, finally keyword 

# Find modulus of two number and 
# handle exception, if divisor is 0

a = 10
b = 3

try:
    # no error
    result = a%b
    print(result)
    
    # assign 0 to b
    # an error will occur
    b = 0
    result = a%b
    print(result)
    
except:
    print("There is an error")
finally:
    print("Finally block, Bye Bye")

Output

1
There is an error
Finally block, Bye Bye	

Example 2

try:
    print("Dividing numbers...")
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution of finally block")

Output

Dividing numbers...
Cannot divide by zero!
Execution of finally block
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.