Throw exception on write failure

Based on the PR #10 by @viniciusbo