For a system described by the canonical ensemble, the energy is an expectation value since we allow energy to be exchanged with the surroundings (a heat bath with temperature \( T \)).
This expectation value, the mean energy, can be calculated using $$ \begin{equation*} \langle E\rangle =k_{B}T^{2}\left(\frac{\partial lnZ}{\partial T}\right)_{V, N} \end{equation*} $$ or using the probability distribution \( P_i \) as $$ \begin{equation*} \langle E \rangle = \sum_{i=1}^M E_i P_i(\beta)= \frac{1}{Z}\sum_{i=1}^M E_ie^{-\beta E_i}. \end{equation*} $$