Stoner avoided the first-corner collision which saw Alvaro Bautista take out riders, Valentino Rossi, Nicky Hayden and Randy De Puniet and somehow overtook Ben Spies on the final corner to win his 10th race of the year.
Monster Yamaha Tech 3 rider Cal Crutchlow managed to finish fourth - the best finish of his MotoGP career - as he claimed the MotoGP rookie of the year award.
The MotoGP riders started the race on slick tyres in difficult conditions as a light drizzle fell over some of the circuit, and there was instant drama as four riders crashed out at the first corner when Alvaro Bautista hit the back tyre of Andrea Dovizioso and slid off, taking Ducati pair Valentino Rossi and Nicky Hayden as well as Randy De Puniet.
Stoner missed the chaos as he surged away from pole position to lead from Dani Pedrosa and Ben Spies. Andrea Dovizioso battled through to take second from Spies.
Spies fought back overtaking both Pedrosa then Dovizioso, Stoner eased off as the rain started to fall heavily Spies closed up with the lead dropping to 1.294 seconds with four laps remaining.
Spies then passed Stoner as the world champion ran wide missing a gear, and the Texan looked certain to win his second race of the season.
But coming out of the last corner Spies took the wrong line allowing Stoner somehow made up the gap to win the final race of the 800cc era by just 0.015 seconds.
Earlier in the day team Gresini rider Michele Pirro won an emotional Moto2 race.
Simoncelli's Gresini team were originally not going to compete in Valencia but decided to take part and Pirro duly won the race to leave team boss Fausto Gresini in tears on the pit wall. Stefan Bradl crashed out of the race but had already won the Moto2 championship.
Valencia MotoGP race result
1 Casey Stoner Repsol Honda 48'18.645
2 Ben Spies Yamaha 48'18.660
3 Andrea Dovizioso Repsol Honda 48'24.581
4 Cal Crutchlow Tech 3 Yamaha 48'27.363
5 Dani Pedrosa Repsol Honda 48'27.966