ROME — Stealing food from a supermarket may not be a crime in Italy if you are homeless and hungry, the nation’s highest appeals court has ruled.

In a case that has drawn comparisons to “Les Misérables,” the Supreme Court of Cassation threw out the conviction of a homeless man from Ukraine, Roman Ostriakov, who was caught trying to take 4.07 euros — about $4.70 — worth of cheese and sausage from a store in Genoa without paying for it. A trial court sentenced him in February 2015 to six months in jail and a fine of €100.

“The condition of the defendant and the circumstances in which the merchandise theft took place prove that he took possession of that small amount of food in the face of the immediate and essential need for nourishment, acting therefore in a state of need,” and therefore the theft “does not constitute a crime,” the appellate court wrote in its decision, which was reported on Monday by the Italian news agency ANSA.

The court’s decision went far beyond what the appeal in the case had sought. Valeria Fazio, the prosecutor at the Genoa court where the trial was held, said in a telephone interview that her office understood that Mr. Ostriakov had stolen only out of need, and had appealed in hopes that the court might set a more lenient sentence.