This is said when something bad happens or something does not happen as we would like, but we feel as if we are actually better off when everything is considered over a long time.
Let us say a friend wanted to take up mountain climbing, but injures his foot before, so he can't go on a dangerous climb. We would say, "Maybe it's all for the best, since he might have been injured more seriously on the climb."