This is not to say that deus ex machina has not been used with success in literature. The best example I could find is in the third book of the Lord of the Rings trilogy. Near the end of Return of the King, Frodo and Sam have delivered the One Ring to Mount Doom and now are surrounded by a rising lava flow moments from being immolated. Suddenly, the Eagles appear and lift them to safety.
If you saw the movie, like me, you probably cheered as the Eagles bore our two heroes away. But, you and I are not J. R. R. Tolkien. Our plots have to make sense, otherwise we risk our audiences putting our books down never to be read again.
Is there ever a time, you may ask, that deus ex machina is permitted? I would answer, “Yes.” In writing about an actual situation, if a deus ex machina moment occurred then, by all means, use it. For example, in the War of 1812, the British army landed near Washington, D.C. and marched into the Capitol city and set about burning it to the ground. The White House and some other Federal buildings went up in flames. But, before they could complete turning the D.C. area into the 19th Century equivalent of a glass paved self-lighting parking lot, a hurricane suddenly appeared putting out the fires and sending the soldiers scurrying back to their ships. If you were writing a historical novel with that War as the background it would be a shame not to include that incident.
But, generally, how do you avoid those deus ex machina scenes in your fiction? You can do this by foreshadowing. You leave hints about solutions to that tricky scene or ending along the way in your story. Don’t make them too obvious, but clear enough so that at the end of that potentially impossible scene or at the conclusion of your work your audience will see how it all ties together and feel nothing but satisfaction as your hero triumphs.
In the James Bond movies there’s always a scene at the beginning with Q, the engineering mastermind of MI-6, in which he gives Bond a host of gadgets to use in his assignment. Invariably, Bond gets out of one after another impossible situation using those quirky devices. This may be a clunky example of foreshadowing, but you get the idea.
Use foreshadowing to extricate yourself from writing a deus ex machina scene. Your story will flow better and your readers will keep reading your work.