PHP中有什么例外,什么是try和catch? [英] What is an exception in PHP for and what is try and catch?

查看:154
本文介绍了PHP中有什么例外,什么是try和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中编写任何东西,而不使用这些,所以什么原因,有什么利益比使用这些东西与传统的方式? >

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"



优点之一是基本思想的一部分)是:


  • 您在中有正常代码尝试

  • ,处理问题代码的最大部分是在 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屋!

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