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

I usually use the following:

  • die "string" for fatal messages you want to directly communicate to the user. I mostly do this in scripts.
  • die $object for full blown exception objects, although most exception classes will have throw method doing that for you. This is for when your caller should be able to tell what kind of error you throw, and maybe even extract information out of it. If you're using Moose, check out Throwable and Throwable-X
  • croak "message" like Adrian said is for when your user has done something wrong, and you want to report the error at whatever called your code. Functions and API level methods are usual cases for this.
  • confess "message" for library errors where I don't see the usefulness of an exception yet. These are usually runtime errors you assume to be a mistake, rather than an exceptional condition. It can make sense to use exceptions for these, especially if you have a large project that uses exceptions already. But it's a good, nice and easy way to get a stacktrace with the error.

If we called the die and croak outside the function there is no difference between these functions.

We can only find difference when we call die and croak within any other function.

croak will gives information about the caller such as function name and line number..etc. die will give error and gives the line number where the error has occured.


It's not necessarily wrong to use die() but croak() gives you or your user a lot more information about what went wrong. There's also variables that can be set in the Carp namespace that can change this output to get more or less information.

It's equivalent to die() but with more information and control.


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.