Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

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 146 views
1 answer 230 views
1 answer 110 views
110 views asked Jan 24, 2024 by avibootz
2 answers 162 views
4 answers 292 views
...