python: return exception from function

Viewed 35435

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?

3 Answers

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
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.

try this one

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