How to bypass error in Blender?
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.