It’s a matter of formula and law.
Let’s take the Eucharist for example.
The priests of the Society of St. Pius X are a group of priests who have been excommunicated latae sententiae, that is, by being a member of this group or receiving Orders from this group, they are excommunicated and are not allowed to celebrate the Eucharist.
HOWEVER, when these priests celebrate Mass and pronounce the words of consecration, the consecration occurs. Their orders are completely valid, but they are not in communion with Rome, so their celebrating the Eucharist is illicit. Compare this to the Anglican Church, whose Orders Leo XIII declared invalid because Henry VIII changed the FORMULA of ordination. Had the Anglican Church maintained the same ordination formula in their Book of Common Prayer, their Orders would be valid (except those “Orders” of women), because the FORMULA would be valid: A validly conscrated priest using a valid formula to ordain a validly qualified man.
For a sacrament to be invalid, there must have been a serious flaw to the formula of its occurance. For example, if a priest changes the words of the consecration, then the sacrament isn’t valid and no consecration occurs.
Adam