What is an exception in PHP for and what is try an

2019-05-07 08:31发布

问题:

I am pretty new to using object/classes in PHP and I am curious about EXCEPTIONS, TRY, and CATCH

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?

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!');
}

try and catch

//and try and catch
try{
    $thumb = PhpThumbFactory::create('/path/to/image.jpg');
}
catch (Exception $e){
    // handle error here however you'd like
}
?>

回答1:

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

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 :

  • 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


回答2:

Exceptions are a way to separate error-handling code from "regular" code. Basically, this strategy lets you write a block of code and not worry about what might go wrong (the try block). Then, later, you catch exceptions that might have been thrown during the block's execution and handle them appropriately. It's a cleaner way to handle errors.