The else block in python is also part of the exception handling. The try block when finds an error, jumps to the catch block. However, we want some behavior when the try block itself is successful.
The response code when the try block is successful is written in the else block. Note that the else block is also used in if-then-else conditional.statements
But, here is if block is replaced with try block and the execution of else block does not depends on the failure of if-block, but on successful completion of the if block.
The above figure suggests that a try except and else block can exist together. If the try is successful , then execute the else block, otherwise, execute the except block because an exception has occurred.
Example Program #1: Exception Handling With Else
In this example program, we try to compare two numbers, if the first number is greater than second number, the python will .multiply these two numbers, else do nothing.
There will be an exception to check
Type Error. Here is the code for the program.
# Read two numbers num1 = int(input("Enter your first number: ")) num2 = int(input("Enter your second number: ")) # try block begins try: if num1 >= num2: print(num1, num2) except TypeError: print("A Type Error Occurred!") else: result = num1 * num2 print("Output = ",result)
In the example above, there is not error because the only error expected is a Type Error. Once the try block finish comparing the numbers –
num2. It jumps to the
else block if
num1 >= num2.
In the else block, we multiple two numbers and display the result.
Example Program #2:
Once common use of python is file handling. You must open a file with correct file name and path before using it. In this example, we will open a file successfully and when it is
open, simply execute the rest of the codes in
Before running this program, create a new file called
myFile.txt in the same directory where you keep your python program.
This program is saved in C:\python_projects\Exception Handling\, therefore, create a file called
myFile.txt in the same directory.
# Program to open a file with else block try: f = open("myFile.txt", "r") except Exception as err: print(err) else: result = f.read() f.close print(result)
After executing the program, you will find that the program return “file read successfully” on the console because we asked the program to read the file and put its content on the console.
open() – It is the function that opens the file and takes two parameters – file name and mode
“r” – It is the mode in which we can do different operations on the file. “r” means read, “w” means write to file, “a” means append to the file.
Output of the Above Program
==== RESTART: C:/Python_projects/Exception Handling/File_Else.py ==== File read successfully >>>
In the next article, you will learn about importance of python finally keyword.
Python Programming: Using Problem Solving Approach
Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.