Subbeh
Subbeh

Reputation: 924

Raise an exception if a specific key exists in a dictionary, but return successfully if it does not exist

Suppose I have the following function:

def test():
  ...
  if x['error']:
    raise

This would raise an exception regardless if x['error'] is defined or not.

Instead if I try this, it doesn't throw any exception:

def test():
  ...
  try:
    if x['error']:
      raise
  except:
    return

How can I test for a specific value and return an exception if it is defined, and to return successfully if it is not defined?

Upvotes: 11

Views: 55715

Answers (3)

Philip DiSarro
Philip DiSarro

Reputation: 1025

def test():
  ...
  if x.get('error'):
    raise

You can avoid unintentionally raising an error using the dictionary's built in get function. Get will return None if the value at the specified key does not exist instead of throwing an exception.

Upvotes: 5

Nouman
Nouman

Reputation: 7303

If you want to return error as string:

>>> def test():
    try:
        if x['error']:raise
    except Exception as err:
        return err

>>> test()
NameError("name 'x' is not defined",)

If you want to an error to occur:

>>> def test():
    try:
        if x['error']:raise
    except:
        raise

>>> test()
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    test()
  File "<pyshell#19>", line 3, in test
    if x['error']:raise
NameError: name 'x' is not defined

Upvotes: 7

vinay
vinay

Reputation: 1416

try this one

def check_not_exist(d,k):
   #if keys exists in dict,raise it
   if k in d:
     raise
   else:
     return True

Upvotes: 0

Related Questions