Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to croak() or to die() when something bad happens in Perl?

Tags:

perlcritic complaints that the following code, some boilerplate DBI stuff that works perfectly fine, should croak instead of die:

# Connect to database my $db_handle = DBI->connect( $url, $user, $password ) or die $DBI::errstr; 

All this, while die seems to work fine for me.

I would think for a samurai Perl warrior, croak is less honorable than actually die when things go awry. Jokes apart

Why should I croak instead of die?

What are the consequences of not heeding perlcritic's advice?

like image 518
GeneQ Avatar asked Nov 11 '10 16:11

GeneQ


People also ask

What does croak do in Perl?

croak() function: This function is similar to die() function, except that it produces a shorter message which reports the error as being from where your module was called. Example: perl.


1 Answers

From http://www.perlmonks.org/?node_id=685452

You use die when the error is something you or your code didn't do right. You use croak when it's something your caller isn't doing right. die "error: $!" indicates the error is on the line where the error occured. croak "error: $!" indicates the error is on the line where the caller called your code.

In this case, the error (connection error to DB) has nothing to do with the caller and everything to do with the line making the connection, so I would use die.

like image 84
Adrian Smith Avatar answered Oct 21 '22 19:10

Adrian Smith