Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Is there any way to cancel initialize object class if there is an error occurs in Python?

$
0
0
class EntityRetrieval(object):    def __init__(self,                 entity_kb_path: str):"""        Args            entity_kb_path: path of entity knowledge base (string) which is json format"""        try:                    entity_kb = json.load(open(entity_kb_path,'r'))        except Exception as e:            logging.error(e)        # Don't use entity type         entity_dict = {}        for entity_type, entities in entity_kb.items():            for entity_id, list_entity_strings in entities.items():                entity_dict[entity_id] = list_entity_strings

Above is my ugly code. Here is what I concern:

  • Does it really need to catch error to prevent crashing? In the above code, the entity_kb_path has to be json file. There might be incorrect format file error, not found file error. And I try to throw message error to user when they not pass in correct argument instead of throw crash.
  • But when I use try catch, the initialization still running and return an instance, I think this is not logical, I mean it should stop initalizing right?
  • If try except puts there then there something weird that the entity_kb variable might not be declared. But the process block code behind that is too long. I might not want to put it in the try block

So how do you do in those scenarios?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>