Catching Exceptions with eval 

sub save_state {
  my($new_state) = @_;

  eval {
    open my $fh, '>', $state_file or die "open($state_file): $!";
    print $fh $new_state          or die "print($state_file): $!";
    close($fh)                    or die "close($state_file): $!";
  };
  if($@) {
    die "Error saving state: $@";
  }
}