How to use multiple exceptions in PHP

2 Answers

0 votes
/*
throw new Exception($error_message);
*/

class customExceptionClass extends Exception 
{
  public function errorMessage() 
  {
        $errorMsg = 'Error on line: ' . $this->getLine() . "<br />" . 
                    'in file ' . $this->getFile() . "<br />" .
                    'Error Message: ' . $this->getMessage() . "<br />";
        return $errorMsg;
  }
}

$email = "test#email.com";

try 
{
  if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    throw new customExceptionClass("email " . $email . " is not valid");
  }
  if(strpos($email, "test") !== FALSE) {
    throw new Exception("$email is a test email");
  }
}

catch (customExceptionClass $e)
{
    echo $e->errorMessage();
}

catch(Exception $e) 
{
    echo $e->getMessage();
}
        
/*
run:

Error on line: 22
in file C:\xampp\htdocs\workingframe.com\test.php
Error Message: email test#email.com is not valid
  
*/

 



answered Jan 4, 2016 by avibootz
0 votes
/*
throw new Exception($error_message);
*/

class customExceptionClass extends Exception 
{
  public function errorMessage() 
  {
        $errorMsg = 'Error on line: ' . $this->getLine() . "<br />" . 
                    'in file ' . $this->getFile() . "<br />" .
                    'Error Message: ' . $this->getMessage() . "<br />";
        return $errorMsg;
  }
}

$email = "test@email.com";

try 
{
  if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    throw new customExceptionClass("email " . $email . " is not valid");
  }
  if(strpos($email, "test") !== FALSE) {
    throw new Exception("$email is a test email");
  }
}

catch (customExceptionClass $e)
{
    echo $e->errorMessage();
}

catch(Exception $e) 
{
    echo $e->getMessage();
}
        
/*
run:

test@email.com is a test email 
  
*/

 



answered Jan 4, 2016 by avibootz

Related questions

1 answer 163 views
1 answer 245 views
1 answer 124 views
124 views asked Jan 24, 2024 by avibootz
2 answers 183 views
4 answers 325 views
...