He retained semen that resulted from an erotic dream and was harmed by that. Should he resort to the ‘secret habit’?
The secret habit is haraam. This has been explained in the answer to question no. 329.
The scholars have stated that it is permissible to resort to the secret habit if that is in order to relieve desire that may lead one to fall into the sins of zina or homosexuality. Similarly it is permissible for the purpose of medical tests if he is single and needs such tests. And it is permissible to resort to it if there is the fear of physical harm due to retention of semen. Perhaps this is what is referred to in the question. In any case, it is not permissible to go beyond the bounds of necessity, and it is not permissible to repeat it, and necessity should be measured without exaggerating.
Shaykh Mansoor al-Bahooti (may Allaah have mercy on him) said:
Whoever masturbates by hand for fear of falling into zina or for fear of physical harm, there is no sin on him if he is not able to get married, not even to a slave woman, and he cannot afford a slave woman, otherwise it is haraam and he should be punished by ta’zeer. End quote.
In Sharh Muntaha al-Iraadaat (3/364) it says:
Whoever masturbates, man or woman, when there is no need, it is haraam to do that and he (or she) should be punished for it by ta’zeer, because it is a sin. If he does it for fear of zina or homosexuality, there is no sin on him, and the same applies, even more so, if he does it for fear of physical harm. End quote.
We applaud you for giving up this bad habit and urge you to remain steadfast in that, and if what you did was only because of the pain, then there is no sin on you in sha Allaah.
And Allaah knows best.