views:

49

answers:

2

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  A: 

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.

avpx
Just remember. The first error that it throws stop the execution. But yeah....
Chacha102
+3  A: 

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 :

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
Pascal MARTIN
thanks for the links, after reading the 2nd one I realize this is something I probably will not learn overnight, it seems somewhat complex as when to use and how exactly to use but this is a good start and I understand what they are doing and for somewhat, thank you
jasondavis
Yep, it's not something you'll learn (and use "wisely") in only one day ^^ But no need to leanr that quick, anyway : it'll come step by step, when you are using those :-)
Pascal MARTIN