Usually the blood goes out of the testis through several veins. Among those are the spermatic veins that draw the blood back toward the abdomen.
Varicocele is a dilation of the pampiniform venous plexus in the scrotum due to a reflux of blood in the spermatic veins to the testis (just like the varices of the legs).
This could be due to defective valves, high pressure where spermatic vein ends, or to compression of the vein by a nearby structure.
It is NOT AT ALL related to erection or to masturbation. And again, we cannot do anything to prevent having varicocele.