How to bypass error in Blender? I have an addon, a part of which takes all selected objects, and if they are rigid-bodies, cycles through them applying &quot;Bake to Keyframes&quot;. When this is done, something else is done.
However, when this is run, it all works fine right up until the last object is Baked to Keyframes, at which point I get an error saying that:
Operator bpy.ops.rigidbody.bake_to_keyframes.poll() failed, context is incorrect
Since it actually does what I want that segment to do (all of my objects are keyframed), this error is even more confusing.
What I think it's trying to do is Bake another object, but which one I don't know.
Here is the relevant piece of code:
for i in range(len(selection)):                     #selection is just all objects selected
                bpy.context.scene.objects.active = selection[i]
                bpy.ops.rigidbody.bake_to_keyframes(frame_start=firstFrame, frame_end=lastFrame, step=1)
    
    
        #scale it by -1 to reverse it
        old_type = bpy.context.area.type
        bpy.context.area.type = 'GRAPH_EDITOR'
        bpy.ops.graph.interpolation_type(type='CONSTANT')
        bpy.context.scene.frame_current = 1
        bpy.ops.transform.resize(value=(-1, 1, 1))
        bpy.context.area.type = old_type
        return {'FINISHED'}

And the console when the error occurs:

I also think it might be an iteration error, as in it tries to bake one of my already-baked objects, but I'm not sure.
Any help as to figuring out how to either fix the error or just entirely ignore it (since it doesn't actually stop anything from happening other than halting my script) would be appreciated.
The error is because one of your selected objects is not a rigid body, maybe a camera or lamp.

Instead of looping through a range and using it for an index, it is better to loop through your list of selected objects. Add a test for whether it has rigid body enabled to prevent the error.

for obj in selected:
    if obj.rigid_body:
        bpy.context.scene.objects.active = obj
        bpy.ops.rigidbody.bake_to_keyframes()


And when you need the index as well as the listed items, use enumerate()

for i, obj in enumerate(selected):
    print(i, obj.name)


But here's the thing, you don't need to use a loop at all. The bake_to_keyframes operator already bakes all selected objects --


  bpy.ops.rigidbody.bake_to_keyframes(frame_start=1, frame_end=250, step=1)
      Bake rigid body transformations of selected objects to keyframes


So you are just repeating the same action multiple times.