mahmood mahmood - 5 months ago 42
Perl Question

Catching an exception for a SQL connection in Perl

Using the Ensembl Perl API, there is a

load_registry_from_db
function which connects to a SQL server. It is stated that it will throw an exception for connection timeouts.

$registry->load_registry_from_db(
-host => 'ensembldb.ensembl.org',
-user => 'anonymous',
-verbose => '1'
);



Exceptions : Thrown if the given MySQL database cannot be connected to
or there is any error whilst querying the database.


I want to know how can I catch that exception via Perl? It is written on the pages that
eval
is the best thing. Is that
eval {$registry}
?

Answer Source

You can definitely use eval:

my $statement_ok = eval {
    $registry->load_registry_from_db(
        -host    => 'ensembldb.ensembl.org',
        -user    => 'anonymous',
        -verbose => '1'
    );
    1;
};

if (! $statement_ok){
    # handle error
    do_something() if $@ =~ /.../;
}

The reason I prefer doing it this way is that something else may have or can clobber $@, so using the true statement will ensure that even if $@ is somehow already set, you're sure to have trapped the specific exception in that code.

Essentially, if the call doesn't throw, $statement_ok will be true.

You can also use an external library such as Try::Tiny, but I must admit, I've never used such a thing, I've always just stuck with eval.