Jails are necessary. A better question would be if they should be punitive. When we look at the USA as an example, punitive jails are not working. If you go to jail, you face experiences that can cause PTSD, you don't go into a system that looks to reform you, you are permanently blacklisted as a criminal, and in many cases you are exposed to long term diseases like hepatitis (or worse). Since there was no effort to try to understand what led to your offense and no plan to resolve it, you are likely to still be stuck in the same situation when you get out. Especially if the underlaying issue was poverty, as you will always have an issue finding a decent job after prison.
If you look at a country like Norway, they have a system that still incarcerates people, but they have a very low rate of incarceration per population and their recidivism rate is 20% vs 76% like the USA. They do this by not seeking to punish first, but to rehabilitate. They try to provide prisoners a chance to make it once they get out, giving them new skills and education, so that they don't fail to go back into society. Of course for crimes that are terrible, like murder, they do have life sentences. They cap them at 21 years, but if you show signs that you are not rehabilitated your sentence can be extended by 5 years repeatedly.
One of the things a Warden of one of the Norwegian prisons said stuck with me, "Every inmate in Norwegian prison are going back to society (at some point). Do you want people who are angry — or people who are rehabilitated?"
I have never been to prison, but 3 of my uncles had gone at one time or another. One became very affected mentally because he was raped multiple times. Until he died a few years ago, he was never right in the head. He also was infected with Hepatitis B, which became chronic, and had it the rest of his life. His younger brother also went, but he bulked up and joined the white gang inside for protection. He had to do a lot of things while inside due to that. It also led to him going back later. The third uncle robbed banks, so he went to Federal prison for 8 years. Once he got out, he basically scammed his family and vanished. None of them were rehabilitated, only exposed to punishment. None of them were better when they came out compared to when they went in. The crazy thing is, prison in the USA has gotten worse since then due to it becoming a corporate and capitalist endeavor. We need to do better.