php中的例外...为什么没有人使用它们? [英] exceptions in php... why nobody uses them?

查看:115
本文介绍了php中的例外...为什么没有人使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢php,而我正在寻找如何使用套接字的例子,我注意到没有一个包含异常处理代码。



以为可能php没有例外...但谷歌告诉我否则。有大量的文章赞扬在PHP中使用例外(我来自Java& C#,我是一个转换),但是在实际的例子中,没有人似乎关心trys / catch。



是因为PHP在以前的版本中没有例外吗?



示例(伪代码):

  $ fp = fsockopen($ allTheNeededParams); 
如果(!$ fp){
//错误处理
}
fwrite($ fp,$ out); //< - 如果这里出现问题,插座从未关闭?
fclose($ fp);

在其他语言中,处理套接字的那一刻,您会看到try / catch遍及整个地方。为什么不在php?



StackOverflow的两个示例:





感谢您的时间!

解决方案

PHP有一个以启示录为主题的错误处理方法:如果出现问题,脚本就会结束,它使用的任何资源(数据库连接,文件,套接字,内存)被运行时释放。这使得它不如处理这些问题的关键,而不是Java或C#,其中服务器代码连续运行;在PHP中,未处理的错误条件意味着单个用户在Java或C#中不方便,这可能意味着资源泄漏最终导致服务器关闭。



当然,PHP的功能库很大一部分已经设置好了,这意味着所有这些函数都使用返回代码和错误报告,而不是例外,PHP中添加了异常。使用异常替换错误不能在库级别(它会打破现有的代码太多),而在代码级别,它是一个艰巨的任务,涉及大量的样板来在沉默时检测错误,并引发异常。 / p>

I'm very new to php and while I was looking for examples of how to use sockets I noticed that none of them included exception handling code.

First I thought that maybe php didn't have exceptions... but google told me otherwise. There are tons of articles praising the use of exceptions in php (I come from Java & C#, I'm a converted) but then, in the real examples, no one seems to care about trys/catches.

Is it due to the fact that php didn't have exceptions in previous versions?

Example (pseudocode):

$fp = fsockopen($allTheNeededParams);
if(!$fp){
   //error handling
}
fwrite($fp, $out);//<-what if something goes wrong here? the socket is never closed?
fclose($fp);

In other languages, the moment you deal with sockets you see try/catch all over the place. Why not in php?

Two examples from StackOverflow:

Thanks for your time!

解决方案

PHP has an apocalypse-themed approach to error handling: if anything goes wrong, the script just ends and any resources it was using (database connections, files, sockets, memory) is freed by the runtime. This makes it less critical to handle such issues than it is in Java or C#, where server code runs continuously — in PHP, an unhandled error condition means a single user is inconvenienced, in Java or C# it might mean a resource leak that ends up bringing the server down for everyone.

And, of course, there's the fact that PHP added exceptions along the way after a huge part of its library of functions was already set in stone, meaning that all those functions use return codes and error reporting instead of exceptions. Replacing errors with exceptions cannot be done at the library level (it would break too much existing code) and at the code level it is an arduous task that involves a lot of boilerplate to detect the error while silencing it, and throw an exception.

这篇关于php中的例外...为什么没有人使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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