0

I have a custom InvalidError, and I want my function handles two kinds of errors: one is InvalidError, the other are all other errors. I tried in this way:

try:
   a = someFunc()
   if a:
      # do things
   else:
      raise InvalidError('Invalid Error!')
except InvalidError as e:
      return "Invalid"
except Exception as ex:
      return "Other"

But seems I will get Other either way. How can I achieve my functionality in right way?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
JasmineOT
  • 1,978
  • 2
  • 20
  • 30

2 Answers2

0

Can you tell us how you created you InvalidError class? It is working.

class InvalidError(Exception):
   pass

>>> try:
...    raise InvalidError("dsfsdf")
... except InvalidError as my_exception:
...    print "yes"
... except Exception as e:
...    print "No"
... 
yes
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
Sanch
  • 137
  • 7
0

One way of doing this would be to create a context manager class. Within the contect manager you can ignore whatever error you like,

E.g.

class ctx_mgr:

def __enter__(self):
    cm = object()
    return cm    

def __exit__(self, exc_type, exc_value, exc_tb):
    return (exc_type == InvalidError)

with ctx_mgr: a = someFunc()

ShaneOC
  • 1
  • 2