Python exception handling: Check return value of function
Question: Before using the value of a return of a function, I want to check if the value
is useable. So what I have is more or less the following:

    
    
    def get_module():
      import foo
      return foo
    
    def do_something():
      try:
        module = get_module()
      except:
        print "error"
    
      module.bar()
    

Unfortunately, it seems to me that this never raises an exception. In
particular, I want to check (a) that the module was transferred correctly and
(b) that the module is one of three possible modules.

I know I can check through if-statements, but I feel that exception handing is
ought to be the correct way.


Answer: If `foo` cannot be imported, the code below will produce an
[ImportError](http://docs.python.org/2/library/exceptions.html#exceptions.ImportError)
exception:

    
    
    def get_module():
        import foo
        return foo
    
    
    def do_something():
        try:
            module = get_module()
        except ImportError:
            print "Import Error!"
            raise
    
        module.bar()
    
    
    do_something()
    

Produces:

    
    
    Import Error! 
    Traceback (most recent call last):
        ...
    import foo 
    ImportError: No module named foo
    

Note, that you should either reraise the exception via `raise` in the `except`
block, or make a `return`, so that you don't get an error on `module.bar()`
line because of undefined `module` variable.

Hope that helps.

