Indeed, one of the main arguments in favor of human colonization of space in real life is that it's a hedge against extinction. A species that settles beyond its own planet is safe from planetary-scale catastrophe, and one that spreads far enough across interstellar space is immune from just about anything that could cause its extinction.
Although it's true that Trek has nonetheless posited the existence of a substantial number of extinct starfaring races, some of whom have been implausibly claimed to have been rendered extinct simply by the destruction of their homeworlds, like the Tkon, the Iconians, and the builders of Mudd's androids. It seems to be a common failure of imagination among Trek writers to forget that an interstellar empire would not have all its population concentrated on a single planet. (See also the dialogue in TUC about the risk of Klingon extinction, and Spock's "endangered species" line from the 2009 movie -- same problem.) But other starfaring races were rendered extinct by more widespread warfare, like the Menthar and Promellians, or by changes in their own biology, like the Loque'eque from the ENT episode that was actually titled "Extinction." And many ancient races are just gone without explanation, so they could've evolved into incorporeal forms rather than just dying off.