How does making stone pelting on trains a punishable offence help in improving railway safety and public behavior?

I want to explore the impact of legal measures on preventing dangerous acts and whether such laws can change how people act near railway tracks.