2

For example i have a program with this structure:

Domain logic module -> Settings module -> Settings store backend

Next is a part of Settings module.

def load_from_json(self, json_str):
    try:
        self.load_from_dict(json.loads(json_str))
    except ValueError as e:
        raise SettingsLoadDataException('Error loading json')

Need I a custom exception SettingsLoadDataException here, or I could just skip catching json.loads errors?

def load_from_json(self, json_str):
    self.load_from_dict(json.loads(json_str))

Update.

Also good variant is:

def load_from_json(self, json_str):
    try:
        self.load_from_dict(json.loads(json_str))
    except ValueError as e:
        raise ValueError('Error loading json')

2 Answers 2

2

That is a problem only you can answer. You could catch all exceptions, or you could let the program crash if it throws an exception you don't handle. If it is vital that the program doesn't crash, catch the exception. However, you should implement a recovery method then. If the Json doesn't load properly, can your program do anything useful without it ? If it can, I would catch the exception, otherwise you could just display an error and terminate.

Sign up to request clarification or add additional context in comments.

Comments

1

You should work with exceptions in such a way, that seeing a stack trace explains the problem to you immediately.

I am no Python expert, but won't you loose the piece of information that it was actually ValueError, that caused program crash? You will see only SettingsLoadDataException in a trace without any real reason of it, right?

Also, if you do not rethrow exceptions, you should catch only those, you know how to deal with. It is always better to have your program crash, than to leave it in an unexpected state.

2 Comments

Yes, i am worried about stack trace. In python is possible to rethrow original stack trace with different exception but it looks like a ugly bicycle. But sometimes i dont need full stacktrace: in example in head i dont want to know where original exception occurs, i just want to know that there is a ValueError('Invalid json'). Need i a custom SettingsLoadDataException or using just a ValueError is more pythonic?
@PavelPatrin Think about being crystal clear for debugging, not being "pythonic" :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.