  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 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 models of the
solar atmosphere, eg in coronal fields reconstructions or numerical
simulations. 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.
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. The quantified errors on energy
vary from negligible to significant errors, depending on the extent of the
nonsolenoidal component. 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. We provide a method of quantifying the effect of a finite
divergence in numerical fields, together with detailed diagnostics of its
sources.
