什么是PHP中的异常和什么是try和catch? [英] What is an exception in PHP for and what is try and catch?
问题描述
我很高兴在PHP中使用对象/类,我非常想知道 EXCEPTIONS , TRY 和 CATCH
I am pretty new to using object/classes in PHP and I am curious about EXCEPTIONS, TRY, and CATCH
在下面的例子中,我使用了所有3。显然一个例外是某种方式触发错误,但我不明白为什么?在下面的代码中,我可以很容易地显示某种错误或没有异常部分的东西。
In the example below I have all 3 shown in use. Obviously an exception is some sort of way of triggering an error but I do not understand why? In the code below I could easily show some sort of error or something without the exception part there?
下面的例子是使用try和catch的例子。在我看来,与使用if / else相同。我可能是错的,这只是我看到他们不知道什么的方式,我意识到你可以在PHP中编码任何东西,而不使用这些,那么什么是什么原因,是否有任何好处,使用这个东西VS传统的方式? >
Below that example is an example using try and catch. It appears to me to be the same as using if/else. I may be wrong, this is just the way I see them without knowing anything, I realize you can code anything in PHP without using these so what is the reason, is there any benefit over using this stuff vs the traditional ways?
<?PHP
// sample of using an exception
if($something === $something_else){
//do stuff
}else if($something === $something_else_again){
//do stuff
}else{
throw new Exception('Something went wrong!');
}
尝试并捕获
//and try and catch
try{
$thumb = PhpThumbFactory::create('/path/to/image.jpg');
}
catch (Exception $e){
// handle error here however you'd like
}
?>
推荐答案
em>
To make things short, an exception is a "special condition that change the normal flow of program execution" (quoting wikipedia)
您可能对(至少)这些文章感兴趣:
You might be interested by (at least) those couple of articles :
- Exception handling - wikipedia
- Exceptional PHP: Introduction to Exceptions
- Exceptional PHP: Extending The Base Exception Class
- Exceptional PHP: Nesting Exceptions In PHP
他们应该给你一些有趣的元素 - 特别是第二个,什么是php中的异常
They should give you some interesting elements -- especially the second one, for "what is an exception in php"
(这是基本想法的一部分)的优点之一是:
One of the advantages (which is part of the basic idea) is :
- 您在
try
块 - 中有正常代码,而且处理问题代码的最大部分在
catch
阻止 - 这意味着在正常代码中间处理问题 >
- ,并允许您重新组合代码的处理问题部分
- you have the "normal" code in the
try
block - and the biggest part of the "dealing with problems" code is in the
catch
block - which means less "dealing with problems" code in the middle of the "normal" code
- and also allows you to regroup "dealing with problems" portions of code
这篇关于什么是PHP中的异常和什么是try和catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!