This question comes up when people don't understand the absolute holiness of God and the fact that we sometimes tend to put God in a box. We have expectations of how we think God should act, however God's ways are far above and beyond man's ways as written in Isaiah 55:8-9:
"For my thoughts are not your thoughts, neither are your ways my ways," declares the Lord. "As the heavens are higher than the earth, so are my ways higher than your ways and my thoughts than your thoughts."
When King David tried to bring back the Ark of the Covenant to Judah from Philistine lands he did not follow God's direct instructions for transporting and handling the Ark. (See 2 Samuel 6:1-7 and 1 Chronicles 13:9-12). God killed Uzzah when the ox stumbled and he took hold of the Ark so it wouldn't fall. God takes the issue of His holiness and the requirement for reverance of His commands very seriously. He described exactly how the Ark was to be built and how it was to be handled and carried in Old Testament passages such as Exodus 25:14-15 and Deuteronomy 10:8. He also warned the Levite priests about capital punishment if they touched anything that was holy.
"And when Aaron and his sons have made an end of covering the sanctuary, and all the vessels of the sanctuary, as the camp is to set forward after that, the sons of Kohath shall come to bear it: but they shall not touch any holy thing, lest they die. These things are the burden of the sons of Kohath in the tabernacle of the congregation." Numbers 4:15
By this incident and other incidents of God punishing people for irreverence and disobedience (such as another incident of profaning the Ark written in 1 Samuel 6:19) God shows people there are dire consequences for their lack of respect for his Holiness. .
For a more in-depth explanation of this subject please visit: Why was Uzzah Killed?
It is difficult to understand why God would order such harsh punishment (stoning of disobedient children in Leviticus 20:9 and Deuteronomy 21:18-21) for seemingly mild crimes. God judged these children severely for several reasons:
- These were extreme examples of contempt of parental authority. If left unchecked, it would lead to the death of the family, law, and order. The question then is: Who or what should die? The rebel, or family and society?
- The life of a rebel inevitably leads to the grave (sheol; cf. Pr. 30:17); he will die an early death, and probably take others with him (see https://chalcedon.edu/magazine/stoning-disobedient-children)
- Rebellious children brought this punishment on themselves. They knew what they were was supposed to do, and did not do it (see https://www.gotquestions.org/stone-rebellious-children.html).