当Perl发生不好的事情时,它是更好的croak()还是die()? [英] Is it better to croak() or to die() when something bad happens in Perl?

查看:650
本文介绍了当Perl发生不好的事情时,它是更好的croak()还是die()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

perlcritic 投诉以下代码,一些样板DBI的东西,工作完美,应 croak ,而不是 die

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.

我会想到一个武士Perl战士,克鲁克比事实变得不实际的死亡不那么荣耀。分开的笑话

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

为什么我应该 croak 而不是 die

Why should I croak instead of die?

不注意的后果是什么? perlcritic's advice?

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

推荐答案

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


你使用死,当错误是你或你的代码不正确。你使用croak当它的东西,你的调用者不正确。 die错误:$!表示错误发生在发生错误的行上。 croak错误:$!表示错误在调用者调用您的代码的行上。

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.

在这种情况下,错误与调用者无关,并且与使用连接的行做一切,所以我会使用 die

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.

这篇关于当Perl发生不好的事情时,它是更好的croak()还是die()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆