It sounds like a bug in handling the layerid correctly for the last layer if one or more layers in the map has broken link to the data. I don't see any workaround other than fixing the broken layer or removing this invalid layer.
here is the bug for this issue: NIM063468