Long story short, I have a substantial Python application that, among other things, does outcalls to ‘losetup’, ‘mount’, etc. on Linux. Essentially consuming system resources that must be released when complete.
If my application crashes, I want to ensure these system resources are properly released.
Does it make sense to do something like the following?
def main(): # TODO: main application entry point pass def cleanup(): # TODO: release system resources here pass if __name__ == '__main__': try: main() except: cleanup() raise
Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?
I like top-level exception handlers in general (regardless of language). They’re a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception.
It’s also a fantastic place to log those exceptions if you have such a framework in place. Top-level handlers will catch those bizarre exceptions you didn’t plan on and let you correct them in the future, otherwise, you may never know about them at all.
Just be careful that your top-level handler doesn’t throw exceptions!