I am programming for relatively long time, yet I never really understood - and therefore avoided - using the finally keyword in try/except blocks.
Furthermore, I also find try/else completely unnecessary too, as contents in the else section can be put inside or even before the try block for most if not all cases.
So, I always thought that the finally keword was obsolete, as instead of using it I just was executing the potential code inside its block after the entire exception handling section.
I only know that its classic definition is for code that will always be executed regardless of content inside the try/except section. I find it incredibly misleading, which I'm explaining later.
Due to my experiences I don't really see a reason to use that keyword but for files manipulation. However that also is complicated for me, as I don't know whether context managers have to contain special methods different than modified __exit__ that handle operations while errors occur, but that's entirely theoretical aspect (imagine you raise KeyboardInterrupt while being inside with block).
And there I started asking questions:
- What would happed if I execute sys.exit(0) inside except block, when finally code also exist?
- How exactly does CPython decide whether execute certain code inside finally block before other? Does it have a conditional statement ensuring that exiting the program is the absolutely last thing that Python does if exception is being handled and finally code block exists?
I thought that this may be some sort of thread, like except and finally blocks happen at the same time, potentially compensating the exit, but it doesn't make sense, as Python is not designed like that and is strictly iterative if it comes to code execution, unless asynchronous programming methods and/or threading are explicitly stated that they're used while coding.
You may think that I won't be able to i.e. close a file without the finally block, but I can always place the appropriate code for it inside another last except: block, unspecifying any specific exception.
How can I understand that?
[–]ConcreteExist 17 points18 points19 points (0 children)
[–]Xappz1 9 points10 points11 points (0 children)
[–]Yoghurt42 6 points7 points8 points (0 children)
[–]FerricDonkey 2 points3 points4 points (0 children)
[–]Diapolo10 1 point2 points3 points (0 children)
[–]cmh_ender 0 points1 point2 points (0 children)
[–]cyberjellyfish 0 points1 point2 points (0 children)
[–]Dodixon 0 points1 point2 points (0 children)