Friday, March 25, 2011

Perl Quick Tip: Catching Fatal Errors with 'eval'

use strict;
use warnings;
use XML::LibXML;

# Initialize the XML parser
my $parser = XML::LibXML->new();

my $tree;
my $file = 'example.xml'; # (Assuming $file is defined somewhere in your script)

# The 'eval' block catches fatal errors so the script can continue running.
eval {
    # Parses the file contents into the new libXML object.
    # If the file is missing or contains invalid XML, this throws an exception.
    $tree = $parser->parse_file($file); 
};

# $@ is a special Perl variable that holds the error message from the last eval block.
# If eval succeeded, $@ will be empty (false). If it failed, $@ contains the error string.
if ($@) {
    warn "Error encountered: $@";
}

No comments: