Added some defensive programming in the sharing code.

This may fix #19924, but maybe not.