Thursday, October 16, 2025
HomeLanguagesHow to retrieve error message using Exception class in PHP when error...

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)
        {
            // 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:

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11953 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS