Hi justspree,
Throw is used when throwing an error inside a function or an Object's method. The code that calls the function/method is wrapped in try/catch blocks ad if an error occurs inside the called function/method the catch part of the block runs and determines how you handle the error. Like:
PHP Code:
function calculateFraction($value){
if(!$value){
throw new Exception('Cannot divide by zero.');
} else {
return (1/$value);
}
}
/*call the function*/
try {
echo calculateFraction(2);
echo calculateFraction(0);
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
/* Outputs */
0.5
Caught exception: Cannot divide by zero.
?>
Steve
Bookmarks