How to retrieve error message using Exception class in PHP when error occurred ?
Exception handling is the important part of PHP in which we deal with how to maintain the flow of the program if there is an error or exception that occurs during the compilation.
As you know we can handle the exception by throw, try-catch, die method so now we understand how to retrieve the error message using exception class by given below examples.
Example 1: In this, we understand how to retrieve the message without class. By using the getMessage() keyword, we can print out the error message for any error that occurs.
PHP
<?php
$i = 0;
while ( $i < 10){
try {
if ( $i < 5)
{
echo "Value of i is $i" . "<br>" ;
$i ++;
}
else {
throw new Exception( "Value of i is greater than 4." );
}
}
catch (Exception $e ) {
echo 'Error Message : ' . $e ->getMessage();
break ;
}
}
?>
|
Output:
Example 2: In this, we understand how to retrieve error messages using class exceptions. First, we pass the email and it goes in try block. If it is not valid then it throws the exception and we can get the error message by writing errormessage(). We can print that error message by catch block as seen in the below message.
PHP
<?php
class customException extends Exception {
public function errorMessage() {
$errorMsg = 'Error Message :: ' . '<b>' . $this ->getMessage().
'</b> is not a valid E-Mail address' ;
return $errorMsg ;
}
}
$email = "gfg@gmail..com" ;
try
{
if (!filter_var( $email , FILTER_VALIDATE_EMAIL)) {
throw new customException( $email );
}
}
catch (customException $e ) {
echo $e ->errorMessage();
}
?>
|
Output:
Last Updated :
09 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...