php OOP异常或die()? [英] php OOP Exceptions or die()?

查看:124
本文介绍了php OOP异常或die()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一些项目。我想控制不同的错误。我知道在所有流行的框架和php项目有不同的异常。但我认为这不是必需的工作。如果错误发生,我们可以使用我们的消息die()。
1.异常的主要优点是什么?
2.我可以用die()控制错误吗?



谢谢。

解决方案

好吧,你可以使用 die()。但这使所有的错误致命。这意味着你不能尝试从错误中恢复。在某些情况下,这很好。



但在大多数情况下,你可能想要在错误后清理的能力,或尝试另一种方法。这是异常派上用场的地方...他们让你选择在哪里和如果你想处理的错误。



例如,假设您有一个从远程服务器下载文件的方法: downloadFromRemoteServer($ address);



如果使用 die()下载失败,脚本终止。



但如果您使用例外,您可以尝试其他伺服器,甚至尝试其他方法(HTTP与FTP等):

  try {
$ file = downloadFromRemoteServer('http://example.com/foo');
} catch(DownloadFailedException $ e){
try {
$ file = downloadFromRemoteServer('http://secondtry.example.com/foo');
} catch(DownloadFailedException $ e2){
die('Could not download file');
}
}
return $ file;

但请记住,异常仅在特殊情况下有用。它们不是用于任何可能的错误。例如,如果用户未正确验证其电子邮件地址,则不是例外。但是如果你不能连接到数据库服务器,或者在数据库中有冲突,这将是一个例外情况...


I am developing some project. And I want to control different errors. I know that in all popular frameworks and php projects there are different Exceptions. But I think that is not required work. If the error is occured we can make die() with our message. 1. What are the main pluses of Exceptions? 2. Can I control my errors with die()?

Thank you.

解决方案

Well, you could use die(). But that makes all errors fatal. Meaning that you cannot try to recover from the error at all. In some cases that's fine to do.

But in most cases, you may want the ability to "clean up" after the error, or to try another method. This is where exceptions come in handy... They let you chose where and if you want to handle the error. They let you try to gracefully recover from the errors.

For example, let's say you have a method which downloads a file from a remote server: downloadFromRemoteServer($address);

If you use die(), if the download fails, the script terminates. End of story.

But if you use exceptions, you could try another server or even try a different method (HTTP vs FTP, etc):

try {
    $file = downloadFromRemoteServer('http://example.com/foo');
} catch (DownloadFailedException $e) {
    try {
        $file = downloadFromRemoteServer('http://secondtry.example.com/foo');
    } catch (DownloadFailedException $e2) {
        die('Could not download file');
    }
}
return $file;

But remember that Exceptions are useful only for exceptional circumstances. They are not meant to be used for any possible error. For example, if a user doesn't verify their email address correctly, that's not exceptional. But if you can't connect to the database server, or have a conflict in the DB, that would be an exception circumstance...

这篇关于php OOP异常或die()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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