In the trial of any contested election, and in proceedings to investigate any election and in criminal prosecutions for violations of the election laws, no person other than a defendant in such criminal prosecutions shall be allowed to withhold his testimony on the ground that he may criminate himself or subject himself to public infamy; but such person shall not be prosecuted for any offense arising out of the transactions concerning which he testified, but may be prosecuted for perjury committed on such examination.