Why do some caterpillars have such funny colors?

Why do some caterpillars have such funny colors?

Caterpillars are often camouflaged in such a way that they match their background, or they may look like something other than a caterpillar.

Papilio_cresphontes.jpg
A giant swallowtail (Papilio cresphontes) caterpillar
whose coloration resembles bird feces.