I'm trying to solve
$$ \int_{-\infty}^\infty \frac{\cos x}{1+x^2}\, \mathrm{d} x,$$
which has been done to death and widely available. What I'm confused with is a particular function I chose and why it won't produce the correct answer $\pi/e$.
For a complex variable $ z $, consider the integral
$$ \int_C \frac{\cos z}{1+z^2}\, \mathrm{d} z, $$
where $ C $ is the usual infinitely large semicircle in the upper-half of the complex plane. There is one pole in this region at $ z = i $, so the integral is equal to $ 2 \pi i \mathrm{Res}(\cos z/(1 + z^2), i) = \pi \cosh(1) $. Now, we can split the integral into 2 portions, one along $ z = x $ and another along $ z = r \mathrm{e}^{i \theta} $:
$$ \begin{align} \int_C \frac{\cos z}{1+z^2}\, \mathrm{d} z &= \int_{-\infty}^\infty \frac{\cos x}{1+x^2}\, \mathrm{d} x + \int_0^{\pi} \frac{\cos\left(r\mathrm{e}^{i \theta} \right)}{1+r^2 \mathrm{e}^{2 i \theta}}\, \mathrm{d} \theta = \int_{-\infty}^\infty \frac{\cos x}{1+x^2}\, \mathrm{d} x = \pi \cosh 1, \end{align} $$
since when $ r \to \infty $, the 2nd integral vanishes. But, this isn't correct, it should be $ \pi/e $. I'm not understanding why this is wrong.
The problem is that your function does not vanish on the semicircle. The reason is that $\cos(z)$ is not bounded by $\pm 1$, and can go to infinity. So you need to express your function is a different way. Say $$\cos(z)=\frac{e^{iz}+e^{-iz}}2$$ Once you split the integral into two parts, you notice that one of the integral will vanish on the upper contour, one will vanish on the lower one. $$\int_{-\infty}^\infty\frac{\cos x}{x^2+1}=\frac12\int_{-\infty}^\infty\frac{e^{ix}}{x^2+1}+\frac12\int_{-\infty}^\infty\frac{e^{-ix}}{x^2+1}$$ We continue the first integral on the upper side, where it will vanish, and the second on the lower side. For the first you need to calculate the residue at $i$, for the second at $-i$. $$\int_{-\infty}^\infty\frac{\cos x}{x^2+1}=\pi i\mathrm{Res}\left(\frac{e^{iz}}{z^2+1},i\right)+\pi i\mathrm{Res}\left(\frac{e^{-iz}}{z^2+1},-i\right)=\pi i\frac{e^{-1}}{2i}+\pi i\frac{e^{-1}}{2i}=\frac\pi e$$