Search code examples
phpexceptiontry-catchthrow

What are some simple examples of using throw, try, and catch for exceptions? I do not have a solid understanding of any of these


So i've already read all of the exmaples on php.net. And none of their exmaples really stuck with me. I know what exceptions are used for, just not how to properly use throw, try, and catch in my code. Also, I was wondering if this was only used for OOP? Or just any PHP code? I have no idea what to do with "throw new exception". All i know is code goes inside try block, and catch is supposed to handle the errors if any occur. Please help!


Solution

  • Using pseudo code since this is useful in more than just PHP.

    Sometimes methods will run into problems that they can't (or don't want to) deal with. Say we have a sendExDrunkenText($ex) method. This expects an $ex argument and will lookup that ex girlfriend and send them a rambling SMS.

    If this method can't find find the $ex supplied an alternative to returning false or the like is to throw some kind of exception:

    if(! exExists($ex)){
        throw NoSuchExException("Cant't find supplied ex");
    }
    

    (As an aside in precompiled languages - i.e. java - you can require that a method calling your method either deals with or rethrows your exception. For this reason imo exceptions are more useful in these languages).

    Now if you are using the above method you may want to take some action if an exception is thrown. In that case you can catch the exception and deal with it appropriately:

    foreach($exList as $ex){
        try{
              sendExDrunkenText($ex);
        }catch(NoSuchExException $exception){
            removeFromAddressBook($ex);
        }
    
    }
    

    Hope this makes sense.