A federal judge on Monday threw out a closely watched lawsuit brought by two California cities against fossil fuel companies over the costs of dealing with climate change. The decision is a stinging defeat for the plaintiffs, San Francisco and Oakland, and raises warning flags for other local governments around the United States that have filed similar suits, including New York City.

The judge, William Alsup of Federal District Court in San Francisco, acknowledged the science of global warming and the great risks to the planet, as did the oil and gas companies being sued. But in his ruling, Judge Alsup said the courts were not the proper place to deal with such global issues, and he rejected the legal theory put forth by the cities.

“The problem deserves a solution on a more vast scale than can be supplied by a district judge or jury in a public nuisance case,” Judge Alsup wrote in a 16-page opinion.

The cities wanted the defendants — including BP, Chevron, ConocoPhillips, Exxon Mobil and Royal Dutch Shell — to help pay for projects like protecting coastlines from flooding.