Try with multiple except

Hi

I’m trying to curve fit some data, and while doing so I have to have fallbacks to catch tricky data. When I try to implement I get a name not defined error.

try:
    #Do some stuff
    print('first')

except FirstFallback:
    #Do something else
    print('second')

except SecondFallback:
    #Do something 'elser'
    print('third')

I get this message: name ‘FirstFallback’ is not defined. Please advice.

You probably haven’t defined the exception class FirstFallback. Or didn’t import the module in which this class is defined.

Are you trying to catch one of two exceptions that “do some stuff” could raise, or do you want to catch one exception, and if that fails, catch its exception? You need nested try statements for that. In both cases, you need to provide one or more valid exception names to catch, which might include a superclass of multiple expected exception types.

try:
    try_this()
except Exception:
    try:
        # First fallback
        try_this_instead()
    except Exception:
        # Second fallback
        one_last_possibility()

The code you attempted tries print('first'), but expects that it could fail in one of two different ways. Either it raises an exception named FirstFallback (which you haven’t defined, hence your error message; it’s not just an informative tag), or it raises SecondFallback (which must be similarly defined). Either way, no exception raised by print('second') or print('third') will be caught, and only one of them will be attempted, so this doesn’t convey the idea of trying the first print, then the second print, and finally the third print if necessary.

Thanks for the info.

My code performs some calculations which sometimes fail (data + model sometimes become ill conditioned in a curve fit). When the curve fit fails I have two fallback set ups to sort of catch all potential situations. The Try Except I tried was just me googling and throwing in what I found to see if it worked. I guess a nested try except should work.

Try:
   primary code...
Except:
   Try:
       fallback one
   Except:
       fallback two

I’ll try this set up.