No matter how dire the situation might seem, there’s always a way out, an escape clause if you will. It’s simply a matter of finding it and using it to your advantage. The Doctor’s good at that, but then he’s had hundreds of years of experience, so perhaps he has an unfair advantage over most people.
Whenever he finds himself in a tight spot, his brain works constantly, calculating probabilities and possibilities, loopholes and boltholes, whatever works. It might look as though he doesn’t know what he’s doing, but most of the time it’s simply that he doesn’t know yet.