Python Exception Handling With Else

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.

Advertisements

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 depend on the failure of if-block, but on successful completion of the if block.

Try-Except-Else 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 – num1 and num2. It jumps to the else block if num1 >= num2.

In the else block, we multiple two numbers and display the result.

Advertisements

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 else block.

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.

Create myFile.txt
# 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.

Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version