When we meet an opened bracket the only thing we can do is to put it atop of the stack:
When we meet an closed bracket we check if at least an opened one previously has been added to the stack - if there is none, we should throw an error:
So far we are able to catch only one type of error - missing opened bracket. To catch another one, we need to wait until we finish traversing a sequence of brackets and check for leftovers in the stack - in this case there are missing closed brackets.