Skip to content
Related Articles

Related Articles

How to retrieve error message using Exception class in PHP when error occurred ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 09 Mar, 2022

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)
        {
            // Display value of i and increment it.
            echo "Value of i is $i"."<br>";
            $i++;
        }
        else{
            // Throw the exception if occurs
            throw new Exception("Value of i is greater than 4.");
           
        }
    }
    catch(Exception $e) {
        
        // Display error message
        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() {
        
      // Error message
      $errorMsg = 'Error Message :: '.'<b>'.$this->getMessage().
        '</b> is not a valid E-Mail address';
      return $errorMsg;
    }
  }
  
  $email = "gfg@gmail..com";
  
  try
  {
    // Check if
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        
      // Throw exception if email is not valid
      throw new customException($email);
    }
  }
  catch (customException $e) {
      
    // Display custom message
    echo $e->errorMessage();
  }
?>

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!