Search code examples
pythonexceptionraise

Re-raise confusion


What is the best approach if I call a function (e.g. foo()) that may raise ValueError or AttributeError, and in case of ValueError I want to provide another way (e.g. call bar()), but in case of AttributeError I want to re-raise the exception?

  1. Re-raise a specific (here AttributeError) exception explicitly?

     try:
         foo() # may raise ValueError or AttributeError
     except ValueError:
         bar()
     except AttributeError:
         raise
    
  2. or just do nothing (re-reises implicitly)?

     try:
         foo() # may raise ValueError or AttributeError
     except ValueError:
         bar()
    

Update 1:

What is the better approach in case of writing a library (at least a module I know it'll be used by different users)? Explicitly re-raise and document the function that re-raises or just document the function (writing that it may implicitly raise a specific exception)?


Solution

  • You can just except the exception without re-raising. In your case, this is not necessary:

     try:
         foo() # may raise ValueError or AttributeError
     except ValueError:
         bar()
    

    Raising again would be useful in a case where you would have to do some cleanup or need to call a function before raising like:

     try:
         foo() # may raise ValueError or AttributeError
     except ValueError:
         bar()
    
         raise