catch exception php code example
Example 1: php try catch
<?php
function test() {
try {
throw new Exception('foo');
} catch (Exception $e) {
return 'catch';
} finally {
return 'finally';
}
}
echo test();
?>
Example 2: try catch php
try {
}
catch(Exception $e) {
}
Example 3: php catch exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division durch Null.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Exception abgefangen: ', $e->getMessage(), "\n";
}
echo "Hallo Welt\n";
?>
Example 4: try catch in php
Try catch comes under exception handeling concept where using this we control the runtime error and modify the message as we want.
function checkdata($number){
if($number > 10){
throw new Exception("Number is greater than 10");
}
return true;
}
try{
checkdata(15);
echo "The number is below 10";
}
catch(Exception $e){
echo "Message :".$e->getMessage();
}
In above code if condition is not satisfied then it will throw exception and which gets caught by catch block and show the error message.
Example 5: php multiple catch exceptions
try
{
}
catch(AError | BError $e)
{
}
catch(Exception $e)
{
}