my $failed; my $seconds = 12; eval{ Config::Simple->import_from("".$path."", \%config) or die Config::Simple->error(); my $dbh = DBI->connect("dbi:mysql::".$config{'MySQL.host'}.":".$config{'MySQL.port'}."", "".$config{'MySQL.user'}."", "".$config{'MySQL.pass'}."", { 'PrintError' => 1, 'RaiseError' => 1 , 'AutoInactiveDestroy' => 1 } ) or die "Could not connect to ". $config{'MySQL.host'} .": ". $DBI::errstr ."\n"; local $SIG{ALRM} = sub { die "db_timeout" }; eval { alarm($seconds); $dbh->do("USE Thanos1983"); # or die "Error: " .dbh->errstr. "\n"; 1; } or $failed = 1; # outer eval catches alarm that might fire JUST before this alarm(0) alarm(0); # cancel alarm (if code ran fast) die "$@" if $failed; 1; } or $failed = 1; if ( $failed ) { if ( defined $@ and $@ eq "TIMEOUT\n" ) { ... } else { print "Error\n" } # some other error } __END__ $ perl test.pl DBD::mysql::db do failed: Unknown database 'Thanos1983' at test.pl line 30. Error