Try, Except and Finally in Python

Try in Python:

We can handle exceptions by using try block and except block. A critical operation that can raise an exception is placed inside the try block and the code handles exception is written in except block. It has the following syntax:

except Exception-name:

Except in Python:

The except block is required with a try block, even if it contains only the pass statement. It has the following syntax:

except Exception:

Finally in Python:

The finally block is used to define clean-up actions that must be executed under all circumstances. The finally block is always executed before leaving the try block. It means that the statements written in the finally block are executed irrespective of whether an exception has occurred or not. It has the following syntax:

write your operations here
This would always be executed

Pre-defined Clean-Up Action: In Python, some objects define standard clean-up actions that are automatically performed when the object is no longer needed. The default clean-up action is performed irrespective of whether the operation using the object succeeded or failed. We have already seen such an operation in file handling. We preferred to open the file using the keyword so that the file is automatically closed when not in use. So, even if we forget to close the file or the code to close it is skipped because of an exception, the file will still be closed.