Think of the task that you always want your program to do, whether it works fine or throws any errors. For example, we use the try operator with the optional — "finally" to perform cleanup actions that must be performed under all conditions.
Cleanup Actions: before exiting the try statement, a finally clause is always executed, regardless of whether any exception has been thrown or not. These are points for defining the cleaning actions to be carried out under all circumstances.
Whenever an exception is thrown and it is not handled by the exception clause, finally occurs first, and then the default error [Code 3] occurs.
Python programs illustrating "Determine Cleanup Actions"
Code 1: Code runs fine and action is taken at the end by clearing
| tr> |
Yeah! Your answer is: 1 I’m finally clause, always raised !!
Code 2: The error is in the code and is carefully handled in a exception . Note that the cleanup action is performed at the end.
| tr> |
Sorry! You are dividing by zero I’m finally clause, always raised !!
Code 3: Code, raise a bug, but we have nothing except a caveat to handle it. So the cleanup is done first, and then the compiler throws an error (default) .
I’m finally clause, always raised !!
Traceback (most recent call last): File "C: /Users/DELL/Desktop/Code.py", line 15, in divide (3, "3") File "C: /Users/DELL/Desktop/Code.py", line 7, in divide result = x // y TypeError: unsupported operand type (s) for //: ’int ’and’ str’
This article is courtesy of Mohit Gupta_OMG