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 241 views
2 answers 285 views
1 answer 134 views
134 views asked Oct 8, 2022 by avibootz
2 answers 192 views
192 views asked Nov 22, 2020 by avibootz
1 answer 195 views
...