E
E
Elvis2018-11-30 16:56:31
Python
Elvis, 2018-11-30 16:56:31

What is the best way to handle exceptions?

Hey!
There is JSON at the input, which has its own structure, but the keys may not have values, for example:
With data, one of the keys looks like this:

"weight":[{"type":1,"value":31.0,"measurement":"g"}]

But sometimes it comes without data: there
"weight":[]
are more than a hundred keys being processed. writing on each try...except is somehow not very good.
Also, the key may not be available at all, then I will get a KeyError error
. Write a separate function with a check and call it for each key?
I would also like to handle it somehow if I haven’t registered any key in any variable, since a new key may appear and then I will know about it and write my own mapping to it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Guest007, 2018-11-30
@Dr_Elvis

Let weight be a key in some data, then:

if 'weight' in data:
    for w in data['weight']:
        t = w['type']
        # и т.д.

If weight is empty, then the loop will not be executed.
So no checks / exceptions are needed here - you have the key itself - check, since this is a list that is either empty or not.

V
Vadim Shatalov, 2018-11-30
@netpastor

See also https://github.com/Deepwalker/trafaret

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question