Exception handling in PHP
Archive - Originally posted on "The Horse's Mouth" - 2010-03-18 11:00:38 - Graham EllisPHP has exception handling - where you can try a block of code; it it completes, that's good and normal, but if something doesn't work in the normal manner an exception is thrown, and a piece of code to mop up the problem is run, in a catch block.
I've written an example to show this ... I have a function that will return the first or second half of an input string, but if the string that's input to it is an odd number of characters long, it can't work so it throws an exception. See that code - the function and the exception handler too - [here].
Here is what I get when I run that code:
Dorothy-2:sj grahamellis$ php exp.php
Ple-ase [use] [various] excep-tions i-n [PHP]
can't cut use in 2
can't cut various in 2
can't cut PHP in 2
Dorothy-2:sj grahamellis$
Exceptions were only added to PHP quite late in the day, so you'll find that many issues with older functions are handled as errors and warnings, but modern OO based functions (and new code you write!) should use exceptions. Exception objects have a number of methods you can run on them - in the example I've given, you'll see that I've used getMessage to find out a description of the exception.