MOCKSTACKS
EN
Questions And Answers

More Tutorials









Python Else & Finally In Try Except

try and except block:


In the try block, we write the code in which an exception might occur, and in except block, we write the code as a result if an exception occurs. This could either be a print statement or the error itself. If no exception occurs, the except block will not execute. The purpose of try and except is to keep the program running either an error or exception occurs. In simple programs, if an error occurs, the program stops its execution and displays the error onto the screen. We can show the error as a string onto the screen by using try and except, and the program could continue its execution after that.

else keyword:-


Now moving on to the else keyword. We use an else keyword to print something in cases where no exception occurs. Suppose that an exception occurred, and the except block is printing the error; likewise, if the exception does not occur, we can print a statement that no error occurred, using an else keyword. Syntax of using else with try and except block is:

try:
    #Run this code
except Exception as error:
    #Execute this code when there is an exception
else:
    #No Exception. Run this code
Note: An else will only run in the case where no exception occurs.

Example


def divide(a, b):
    try:
        print(f'{a}/{b} is {a / b}')
    except ZeroDivisionError as e:
        print(e)
    else:
        print("No Exception")
divide(1, 2)

Output

1/2 is 0.5
No Exception

finally:-


Now the last keyword for this tutorial, i.e., finally, will run in either case. It is also known as code cleaner because it will perform its action, either an exception occurs or not. We write such commands in the finally part of the code that we want to execute, even an exception occurs or not. It is mostly used to clean resources or close files.

try:
    #Run this code
except Exception as error:
    #Execute this code when there is an exception
else:
   #No Exception. Run this code
finally:
   #Always run this code


1. In the try block, all the statements are executed until an exception occurs.
2. Except block is used to catch and handle the exception(s) that occurs during the execution of the try block.
3. Else block runs only when no exceptions occur in the execution of the try block.
4. Finally block always runs; either an exception occurs or not.

Example



f1 = open("harry.txt")

try:
    f = open("does2.txt")

except EOFError as e:
    print("Print eof error aa gaya hai", e)

except IOError as e:
    print("Print IO error aa gaya hai", e)

else:
    print("This will run only if except is not running")

finally:
    print("Run this anyway...")
    # f.close()
    f1.close()

print("Important stuff")


Conclusion

In this page (written and validated by ) you learned about Python Else and Finally In Try Except . What's Next? If you are interested in completing Python tutorial, your next topic will be learning about: Python Coroutines.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.