Reputation: 24815
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}
?
Upvotes: 2
Views: 216
Reputation: 9306
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
.
Upvotes: 2