Saturday, February 9, 2019

Try .. Except .. Finally

To deal with errors (or exceptions) during run-time we can use try statement in python. The try statement lets us catch the exception and pass the control to the except block, without stopping the program abruptly.

In the following program, the try block will raise an exception as we are trying to print a which is undefined.

try:
print(a)
except:
print("Variable not initialized.")
view raw TryExcept01.py hosted with ❤ by GitHub
There are various kinds of exceptions like KeyboardInterrupt, ZeroDivisionError, OSError, ValueError etc. The following program will raise a ValueError exception is we input a value which is not an integer.

while True:
try:
num = int(input("Enter a number: "))
break
except ValueError:
print("Not a valid number. Try again...")
view raw TryExcept02.py hosted with ❤ by GitHub
We can use as many except block as we need for different exceptions.

The Else block:

The control passes to the else block if no exceptions are raised in the try block. The program below raises a ZeroDivisionError exception if the denominator is zero. Otherwise passes the control to the else block to print the result.

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a/b
except ValueError:
print("Entered values are not integers.")
except ZeroDivisionError:
print("Denominator cannot be zero.")
else:
print("The result is:", result)
view raw TryExcept03.py hosted with ❤ by GitHub
The Finally block

The finally block gets executed regardless of an exception occurred or not. In the program below, we have added a finally block to the same program.

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a/b
except ValueError:
print("Entered values are not integers.")
except ZeroDivisionError:
print("Denominator cannot be zero.")
else:
print("The result is:", result)
finally:
print("End of try.")
view raw TryExcept04.py hosted with ❤ by GitHub

No comments: