First fully working version with exception handling