Articles

Exceptions in PHP code try cat

PHP Exceptions OOP code Tutorials PHP

Learn how to use try and catch in PHP programming.

Exceptions in PHP are used to change the regular flow of the script if a specific error orrurs.

When an exception is triggered the code state is saved. The code exectuion switches to the exception handler function. Depending on what is specified in the function the code state can either terminate the exectuion of the script of continue the script from another location in the code.

Exceptions should be used within error conditions and not general use to move to another location of code exectuion.

Use of Exceptions
When an exception occurs the code will stop exceuting its script. It will then try to find the matching catch block and either continue from there or stop the exectuion. If there is no catch block to catch the exection you will see an uncaught exception error messge.

Correct Exception code should incluide a Try, Throw and Catch.

Try - An attempt to check if an exception will trigger, if it does not the code will conitue to exectue. However if the exception triggers it will throw an error. Throw is how you trigger an exception. Every Throw must have a Catch. Catch retrives an exception and creates an object which continans the information from teh exception.

<?php
function validName($name) {
if(strlen($name)<5) {
echo 'Length of Name:'.strlen($name).'<BR>';
throw new Exception("Expection Message");
}
return true;
}
try {
validName('test');
echo 'No Exception : Name passed Length Test.';
}
catch(Exception $e) {
echo 'Exception Thrown : ' .$e->getMessage() .'<BR>';
}
?>

OUTPUT

Length of Name:4
Exception Thrown : Expection Message

If we change the validName to testmessage the exception will no longer be thrown.

<?php
function validName($name) {
if(strlen($name)<5) {
echo 'Length of Name:'.strlen($name).'<BR>';
throw new Exception("Expection Message");
}
return true;
}
try {
validName('testname');
echo 'No Exception : Name passed Length Test.';
}
catch(Exception $e) {
echo 'Exception Thrown : ' .$e->getMessage() .'<BR>';
}
?>

OUTPUT

No Exception : Name passed Length Test.