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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to use try, throw and catch in PHP

3 Answers

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

function checkZero($n) {
  if($n == 0) {
    throw new Exception("Value must be > 0");
  }
  return true;
}

try {
  checkZero(0);
  echo 'If you see this line, the exception is not thrown';
}

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

Error Message: Value must be > 0 
  
*/

 





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

function checkZero($n) {
  if($n == 0) {
    throw new Exception("Value must be > 0");
  }
  return true;
}

try {
  checkZero(1);
  echo 'If you see this line, the exception is not thrown';
}

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

If you see this line, the exception is not thrown 
  
*/

 





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

try {
    throw new Exception("error message");
    echo 'You will not see this line';
} 
catch (Exception $e) {
    echo 'Error: ',  $e->getMessage();
}
        
/*
run:

Error: error message 
  
*/

 





answered Jan 3, 2016 by avibootz

Related questions

1 answer 111 views
2 answers 111 views
1 answer 30 views
30 views asked Oct 8, 2022 by avibootz
2 answers 70 views
70 views asked Nov 22, 2020 by avibootz
...