Ending years of debate and delay, Gov. David A. Paterson on Friday signed into law a bill shielding sexually exploited girls and boys from being charged with prostitution.

The law, known as the Safe Harbor for Exploited Youth Act, will divert children under the age of 18 who have been arrested for prostitution into counseling and treatment programs, provided they agree to aid in the prosecution of their pimps.

It has been the subject of intense debate in the State Legislature and beyond, and was opposed by some law enforcement officials and by the Bloomberg administration, which argued that the bill would make it harder to crack down on prostitution.

But the bill’s backers said it was wrong to treat under-age prostitutes — many forced into the sex trade and kept there with physical threats and abuse — as criminals rather than victims.

“For too long, these young people have been sexually exploited by pimps and predators, and then exploited again by state law, which treated them as criminals instead of victims,” said Assemblyman William Scarborough, a Queens Democrat who sponsored the bill.

The legislation passed the Democrat-controlled Assembly several times in recent years but died in the Republican-controlled State Senate, most recently because of disagreement over language addressing whether judges would have any discretion over diverting criminal charges.

But supporters agreed to add provisions this year that allow charges to be reinstated if the arrested child refuses counseling or declines to cooperate with court mandates, like testifying against sex traffickers. The new law will also prevent anyone who has already been through the program from avoiding prosecution for later prostitution offenses.