BP PLC took a $25.5 billion pretax accounting charge related to its decision to exit its Russia holdings, including its stake in government-controlled oil producer Rosneft, by far the biggest financial hit tallied by companies pulling back from the country after its invasion of Ukraine.

The London-based company said Tuesday that the charge dragged it into a $20.4 billion headline loss for the first quarter despite soaring commodity prices that poured cash into major oil companies’ coffers. The loss included a $13.5 billion write-down of BP’s nearly 20% stake in Rosneft that reflected its carrying value as of Feb. 27.

Apart from the Russia-linked charges, which had been previously flagged, BP’s results beat analysts’ expectations, helped by what the company called “exceptional” results in oil-and-gas trading. Higher and more volatile prices, together with robust demand, have boosted results for companies that buy and sell commodities globally.

BP shares rose 3% in morning trading in London.

The company said it would buy back another $2.5 billion of its shares, in addition to $1.6 billion in buybacks it made during the first quarter, and that the Russia-related losses don’t change the company’s strategy or cut into its plans to distribute cash to investors. That follows moves by Exxon Mobil Corp. and Chevron Corp. last week to increase shareholder returns amid strong quarterly profits. Exxon tripled its share-buyback program this year to $30 billion, and Chevron said it would buy back a record $10 billion of its shares by year-end.

Soaring commodity prices are leading to piles of cash on major oil companies’ books. But some of the biggest companies aren’t using most of that cash to increase production. After years of lackluster returns, they are favoring dividend and buyback increases.

BP said that without the one-time charges, its first-quarter underlying replacement-cost profit, a metric similar to net income that U.S. oil companies report, was $6.2 billion. That compared with a $4.5 billion average projection of 26 analysts compiled by BP. The results followed a 2021 full-year profit that was BP’s strongest in nearly a decade and a swing back from a 2020 loss of almost $5.7 billion.

The company said it would continue to reduce debt and maintain its full-year capital-spending plans at $14 billion to $15 billion, including $2.9 billion in capital expenditures in the first quarter.

Active debate in the U.K. about potential so-called windfall taxes on oil-and-gas companies had led some analysts to predict British oil giants BP and Shell

PLC would constrain share buybacks relative to U.S. peers. U.K. and other European government officials have been urging energy companies to spend large portions of their cash piles on renewable energy in the U.K. and elsewhere. But the political tensions also are centered on issues that long-term green-energy projects don’t immediately address: Electricity prices were soaring across Europe even before Russia invaded Ukraine, while energy companies have been earning record profits as energy demand bounces back from pandemic lows.

Reflecting the political pressures facing cash-laden energy companies, BP on Tuesday emphasized its role as U.K. taxpayer and said it would dedicate a greater share of its overall spending close to home than it historically has. Alongside earnings, the company said it would continue to invest in oil-and-gas production in the North Sea, and increase spending on lower-carbon energy including offshore wind, hydrogen and electric-vehicle charging. BP said its U.K. energy investments could reach $22.6 billion by 2030.

BP also said it would continue to share profits with investors. “We make more money at higher oil prices, and we use that to reward pensioners,” BP Chief Executive Bernard Looney said in an interview.

Mr. Looney said BP could shift some short-term investments “around the margin” to oil-and-gas production in the North Sea and the U.S. to help meet acute energy needs. “These are things that become probably more attractive in today’s world,” he said.

Meanwhile, companies that have done business for decades in Russia are reckoning with costly withdrawals from the country. BP said Feb. 27 it would exit its 19.75% Rosneft stake and other joint ventures in the country, days after Russian tanks crossed into Ukraine. It hasn’t said how or when it plans to divest the assets.

The invasion has put pressure on companies ranging from fast-food restaurant operators to makers of cosmetics, cars and drugs to cut ties with Russia, while sanctions have complicated operations in the country. More than 750 companies have said publicly they would cut back operations in Russia beyond the minimum changes required by international sanctions, according to researchers at Yale University.

Now the price tags of divorcing from Russia, in many cases ending collaboration decades in the making, are becoming clearer as companies report their first quarterly earnings since the invasion.

While many companies are writing down the value of their Russian assets, others still have operations and workers in the country. General Electric Co. recorded a $200 million impairment charge last week and still has about $600 million in assets in the country that don’t relate to sanctioned activity. GE suspended most of its Russia operations in early March but said it would still provide essential medical equipment and support existing power services in the region.

Others have flagged potential costs still to come. For instance, France’s Renault SA is in talks with Moscow about handing over its 68% stake in Russia’s biggest auto maker to a state-backed entity for the symbolic sum of one ruble, Russian state media reported last week. Renault said in March it was assessing options and planned to write off the value of its Russian activities, which were valued at 2.2 billion euros, equivalent to $2.4 billion, at the end of last year.

So far, though, energy giants have reported the largest costs.

France’s TotalEnergies SE, which has said it is curtailing but not necessarily exiting its Russian operations, last week took a $4.1 billion accounting charge on the value of its natural-gas reserves. Total cited impacts from Western sanctions targeting Russia on a massive Arctic liquefied natural gas project under development called Arctic LNG 2.

On Friday, Exxon said it took a $3.4 billion accounting charge after it decided to halt operations at its Sakhalin Island development in Russia’s Far East.

Shell, which is scheduled to report earnings Thursday, said last month it expected to book accounting charges of up to $5 billion in the first quarter related to its decision to exit its Russia operations, including joint ventures with energy giant Gazprom PJSC.

BP was the most exposed of oil-and-gas majors to Russia, according to analysts. Its Rosneft stake brought it $640 million in dividends in 2021. Analysts previously expected 2022 dividends, paid twice a year, to be worth well over $1 billion. The company’s Russia presence goes back 30 years, and the BP-Rosneft strategic partnership dates back more than two decades.

BP’s February decision to exit Russia meant Mr. Looney and former CEO Bob Dudley immediately resigned from Rosneft’s board, on which both represented BP. BP previously relied on Rosneft for roughly one-third of its oil-and-gas production, but didn’t contribute capital to Rosneft.

Asked whether he can envision BP ever returning to doing business in Russia, Mr. Looney reiterated the company’s exit plans, adding, “We have made our intentions incredibly clear.”

Write to Jenny Strasburg at jenny.strasburg@wsj.com