Undefined variable $written causes fatal error. When an exception is immediately caught on the first fwrite, $written has not been defined yet and the fatal error occurs.