Nonlinear optics of semiconductors is an important field of fundamental and applied research, but surprisingly the role of excitons in the coherent processes leading to harmonics generation has remained essentially unexplored. Here we report results of a comprehensive experimental and theoretical study of the three-photon process of optical second-harmonic generation (SHG) involving the exciton resonances of the noncentrosymmetric hexagonal wide-band-gap semiconductor ZnO in the photon energy range of $3.2$--$3.5$ eV. Resonant crystallographic SHG is observed for the $1s(A,B)$, $2s(A,B)$, $2p(A,B)$, and $1s(C)$ excitons. We show that SHG signals at these exciton resonances are induced by the application of a magnetic field when the incident and the SHG light wave vectors are along the crystal $z$ axis where the crystallographic SHG response vanishes. A microscopic theory of SHG through excitons is developed, which shows that the nonlinear interaction of coherent light with excitons has to be considered beyond the electric-dipole approximation. Depending on the particular symmetry of the exciton states SHG can originate from the electric- and magnetic-field-induced perturbations of the excitons due to the Stark effect, the spin as well as orbital Zeeman effects, or the magneto-Stark effect. The importance of each mechanism is analyzed and discussed by confronting experimental data and theoretical results for the dependences of the SHG signals on photon energy, magnetic field, electric field, crystal temperature, and light polarization. Good agreement is obtained between experiment and theory proving the validity of our approach to the complex problem of nonlinear interaction of light with ZnO excitons. This general approach can be applied also to other semiconductors.