Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise exception if None value encountered in dict?

I want to raise a KeyError exception if the value returned is None, but the following throws a SyntaxError: invalid syntax exception.

try:
   protocol = serverInfo_D['protocol'] or raise KeyError("protocol not present")
except KeyError:
   print "Improper server config"

What's a simple way to get this working?

like image 648
goutham Avatar asked Dec 23 '10 09:12

goutham


People also ask

How do you get a value from a dictionary in a way that doesn't raise an exception for missing keys?

To avoid getting an exception with undefined keys, we can use the method dict. get(key[, default]). This method returns the value for key if key is in the dictionary, else returns default. If default is not provided, it returns None (but never raises an exception).

What does dict return if key doesn't exist?

Python: check if dict has key using get() function If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.

How do you fix KeyError 0?

The Python "KeyError: 0" exception is caused when we try to access a 0 key in a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.

How do I skip a KeyError in Python?

Use a try/except block to ignore a KeyError exception in Python. The except block is only going to run if a KeyError exception was raised in the try block. You can use the pass keyword to ignore the exception.


1 Answers

You're getting a SyntaxError because raise is a statement not an expression, so the or raise KeyError part doesn't make [syntactic] sense. One workaround is to put just that into a function like the following, which is only called if the looked-up value is something non-True, like None, 0, '', and [].

Caveat: Note that doing this is potentially confusing since what it effectively does is make the presence of any of those types of values appear to be as though the protocol key wasn't there even though technically it was...so you might want to consider deriving your own specialized exception class from one of the built-ins and then deal with those instead of (ab)using what KeyError normally means.

def raise_KeyError(msg=''): raise KeyError(msg)  # Doesn't return anything.

try:
    protocol = serverInfo_D['protocol'] or raise_KeyError('protocol not present')
except KeyError:
    print('Improper server config!')
like image 89
martineau Avatar answered Oct 12 '22 04:10

martineau