It depends on their ability to understand their crime at the time they committed it.
Just like a baby doesn't understand that hitting is wrong... some illnesses affect an adult in a way where they black out and have no knowledge of what they did. In this case, they can't be held criminally liable - but they can be forced to go to hospital and get whatever treatment they need to get better.
IF the mental illness is known, and IF society fails to make sure the mentally ill criminals are committed and on meds, then there is an element of shame on society...but it is still no excuse.