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.

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.

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.

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.

No comments: