Python: try … except … else and try … finally

DevTechie
DevTechie
Published in
6 min readMay 21, 2024

--

Python: try … except … else and try … finally

In Python, exception handling allows you to gracefully handle errors or unexpected situations that might occur during program execution. Let’s dive a little deeper into exception handling with this article. The article explains usage of else andfinally clauses with the try … except construct.

try … except … else

Consider the below code which does some calculation in try block based on user input. The try block statement may run into errors. Different except blocks handle different errors (exceptions). The else block does the job of printing the result of the calculation when there is no error in the try block. The code inside the else block may need to be moved within the try block if you are not using the else block.

Code:

total_marks = 500
try:
obtained_marks = eval (input ('Enter a number: '))
result = total_marks/ obtained_marks #ZeroDivisionError


except ZeroDivisionError: # if user entered 0 for obtained_marks
print ("You are trying to divide by 0. Not possible!")

except NameError: # if user entered a value other than 0 for obtained_marks
print ("A name is not defined ")
else:
print ("Percentage result= ", 1/result * 100)

--

--