Added exception handling for KeyError