Search code examples
pythonexceptionrope

Pythonic way to catch all exceptions from a module?


I am trying to do some refactoring using rope package. Depending on the code, it might throw exceptions and there are more than 10 rope exceptions.

I dont want to do

from rope.base.exceptions import *

try:
    # do something
except (AttributeNotFoundError, ModuleDecodeError,
        ..., ..., ..., RefactoringError) as e:
     # do something else

I just want to catch all rope exceptions, something like this

import rope

try:
    # do something
except rope.base.exceptions.*:
    # do something else

How to catch all exceptions from a specific module?


Solution

  • Just catch the base of all of the exceptions:

    In [5]: import rope.base.exceptions as rbe
    In [6]: try:
       ...:     raise rbe.AttributeNotFoundError
       ...: except rbe.RopeError, e:
       ...:     print "RopeError -", e
       ...:
    
    RopeError!