Posted on Leave a comment

Jyrone Parker Live – Exceptions/Error Handling

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]
 

Exceptions and Error Handling

Continuing in the PHP tutorials I am showing you how to throw exceptions and handle errors in PHP. Often times when you are building software you have to account for when things go wrong. To ensure the best experience for your user, you want the application to gracefully handle those errors instead of crashing and leaving the user quizzically stumped. This is where exceptions come in. If you account for the cases where things might break and throw an exception then you can use the try/catch  control structure to catch said exceptions and handle them accordingly. A quick example is such:


<?php
function getRandomRange($min,$max){
if($min < 0){
throw new Exception("Min must be greater than 0");
}
if($max > 10000){
throw new Exception("Max must be less than 10000");
}
return rand($min,$max);
}
try{
/*
php exceptions.php $mix $max
*/
echo getRandomRange($argv[1],$argv[2]) . "\n";
}
catch(Exception $e){
echo $e->getMessage()."\n";
}
?>

Exceptions are part of the global PHP namespace and you can even create your own version on an exception that extends from the Exception class. If you didn’t get a chance to watch my live stream on the subject I talk about it more in depth, you can find it below
[youtube width=”100%” height=”100%” autoplay=”false”]https://www.youtube.com/embed/IkWK3qZ5Ix4[/youtube]