My attempt...

This is my attempt to answer the problem + a bit of exception handling.