Filming water scenes is notoriously difficult, but there is a huge range of tips and tricks that can be used to achieve the results the filmmaker wants in a safe manner. One of the most popular techniques is the use of editing and shot selection. Often the filmmakers will establish the location/scene through a wide shot — for example, we see a ship floating out at sea. Then they cut to inside the boat, or the actor floating in water — this shot is done in a completely different location, such as a shallow swimming pool or other controlled location.
In situations where the actors are physically filmed underwater, they often use a specialized type of rig that can be easily raised out of the water if something goes wrong. There is also typically several medical personnel with oxygen readily available in case something goes wrong.
As an example, check out this interview with Christopher Nolan discussing his approach to filming some of the water scenes in DUNKIRK - https://youtu.be/FNAFHMyXBNA?t=3139 (fast forward to 52:15).