In the movie, the robot shark appears from the ocean after sucking up a school of tuna and attacks the peach. It fires multiple harpoons and biting missiles which penetrate the peach and cut the threads that connected the stem to the seagulls that were carrying the peach.
The Centipede loses his balance due to the shaking of the peach from the impact and falls. He grabs the wire cable of the harpoon and slips down close to machine's mouth. Mrs. Ladybug and Miss Spider subsequently use hammers to break the harpoon and release the giant peach.
After the Centipede manages to escape back up the cable, the harpoon gets stuck inside the shark's mouth after Miss Spider and Mrs. Ladybug release it, jamming and breaking its turbines of teeth. With the turbine clogged, the machine's inner mechanisms clash with each other and break apart, causing it to explode and sink.
In the original book by Roald Dahl, the group was attacked by a massive group of normal sharks that ate at the peach. It is unknown why it was changed to a giant robot in the film, but it may have been to make a more compelling and intense scene than a group of normal sharks. It might also have been to make animation easier, as it would probably be very difficult to animate a bunch of sharks with stop-motion.
The shark's existence is unusual, as it is unknown how and why it was created or even if it was a figment of James' imagination.
It is also possible that the shark was built by Spiker and Sponge to bring James back in case he tries to escape, as when it rises out of the sea, it spouts several plates of the same rotten fish heads they tried to serve him the other day after it sucks up a school of tuna.