Context. For magnetically driven events, the magnetic energy of the system is the prime energy reservoir that fuels the dynamical evolution. In the solar context, the free energy (i.e., the energy in excess of the potential field energy) is one of the main indicators used in space weather forecasts to predict the eruptivity of active regions. A trustworthy estimation of the magnetic energy is therefore needed in three-dimensional (3D) models of the solar atmosphere, e.g., in coronal fields reconstructions or numerical simulations. Aims. The expression of the energy of a system as the sum of its potential energy and its free energy (Thomson's theorem) is strictly valid when the magnetic field is exactly solenoidal. For numerical realizations on a discrete grid, this property may be only approximately fulfilled. We show that the imperfect solenoidality induces terms in the energy that can lead to misinterpreting the amount of free energy present in a magnetic configuration. Methods. We consider a decomposition of the energy in solenoidal and nonsolenoidal parts which allows the unambiguous estimation of the nonsolenoidal contribution to the energy. We apply this decomposition to six typical cases broadly used in solar physics. We quantify to what extent the Thomson theorem is not satisfied when approximately solenoidal fields are used. Results. The quantified errors on energy vary from negligible to significant errors, depending on the extent of the nonsolenoidal component of the field. We identify the main source of errors and analyze the implications of adding a variable amount of divergence to various solenoidal fields. Finally, we present pathological unphysical situations where the estimated free energy would appear to be negative, as found in some previous works, and we identify the source of this error to be the presence of a finite divergence. Conclusions. We provide a method of quantifying the effect of a finite divergence in numerical fields, together with detailed diagnostics of its sources. We also compare the efficiency of two divergence-cleaning techniques. These results are applicable to a broad range of numerical realizations of magnetic fields.