How to handle a custom scenarios during dynamic import in Python 2.7?
I need some guidance on I'm sure I'm missing something obvious here, but I'm working with an scenario with dynamically importing a module in Python 2.7. I'm using the built-in `__import__` function to load a module based on user input. However, when the module isn't found, I want to raise a custom behavior instead of the standard `ImportError`. Here's what I've tried: ```python class ModuleNotFoundError(Exception): pass def dynamic_import(module_name): try: module = __import__(module_name) return module except ImportError: raise ModuleNotFoundError('The module {} could not be found.'.format(module_name)) # Example usage try: my_module = dynamic_import('non_existent_module') except ModuleNotFoundError as e: print(e) ``` When I run this code, I receive the custom behavior message as expected for a non-existent module. However, if the name is misspelled in a different context (say, when the name is passed from a user input), I still get the standard `ImportError` message before my custom behavior is raised. This is confusing for my users. Is there a way to catch the ImportError globally so that my custom behavior message is the only one displayed? Additionally, how can I improve the behavior handling in this case without modifying too much of my current implementation? I'm working on a web app that needs to handle this. This is part of a larger microservice I'm building. How would you solve this? This is happening in both development and production on Windows 11. What would be the recommended way to handle this? This issue appeared after updating to Python LTS. Thanks for your help in advance!