Catching exceptions with eval
sub save_state { my($state) = @_; eval { open my $fh, '>', $state_file or die "open($state_file): $!"; print $fh $state or die "print($state_file): $!"; close($fh) or die "close($state_file): $!"; }; if($@) { die "Error saving state: $@"; } }