A federal judge ruled that law-school graduates who file for bankruptcy protection can cancel the debt they racked up while studying for the bar exam, finding such loans are different from traditional federal student loans that are rarely canceled by bankruptcy.

In an opinion filed Thursday, Judge Carla Craig of the U.S. Bankruptcy Court in Brooklyn, N.Y., said bar-exam loan debt is “a product of an arm’s-length agreement on commercial terms” and doesn’t fall into the category of a student loan that sticks with a borrower...