A wasp came and stung the ostracized scholar on his penis and he died. Because he was a great Torah scholar, they took him into the caves in which the pious are interred in order to bury him there, but the caves did not accept him. A snake stood at the entrance of the caves and did not let them pass. They then took him into the caves of the judges, and they accepted him.
The Gemara asks: What is the reason that he was accepted there? The Gemara answers: Even though he sinned, he still acted in accordance with the opinion of Rabbi Ilai, as it is taught in a baraita: Rabbi Ilai says: If a person sees that his evil inclination is gaining control over him and he cannot overcome it, then he should go to a place where he is not known. He should wear black, and he should wrap his head in black, as if he were a mourner. Perhaps these changes will influence him, so that he not sin. Even if these actions do not help, he should at least do as his heart desires in private and not desecrate the name of Heaven in public. Although this person had sinned, he did so in private and in a manner that did not publicly desecrate God’s name, and therefore it was fitting that he be given an honorable burial.
Talmud, Moed Katan 17a