"finally" - clause





Hello Folks...!!!
Today let us look at the concept of the keyword finally.

finally in python

  • Like try-except, finally is also a clause.
  • It contains the block of code that will be executed irrespective of errors in the code.
  • The try block works if no run-time error occurs, except block is executed if any run-time error occurs but finally is executed when no error occurs and also when error occurs.
  • This is mostly used to clean up the resources used in the program.
  • When you do file operations, irrespective of the errors, opened file should be closed at the end. To do this kind of actions finally block can be written in the code.
Look at the example below.

finally is executed when try block is executed.


It is executed even if except block works.


finally clause can be written even while handling multiple exceptions. It would work even when either of the exception is handled. For example look below.


Not only while using predefined exception handling, finally can be combined with user-defined exception handling also.





Exercise:
Try creating a user-registration system. For simplicity just have two fields user name and password. Set various criteria to ensure the password is strong. For example password must be of length 8 atleast. It should have atleast one capital letter, one number and one special character. In this way define your own constraints and handle then using try-except and finally.



Next TopicπŸ‘‰

Comments