CodeToLive

PHP Error Handling

Basic Error Handling


<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(5, 0);
} catch(Exception $e) {
  echo "Unable to divide: " . $e->getMessage();
}
?>
      

Custom Exception


<?php
class CustomException extends Exception {
  public function errorMessage() {
    return "Error on line " . $this->getLine();
  }
}

try {
  throw new CustomException("Something went wrong");
} catch (CustomException $e) {
  echo $e->errorMessage();
}
?>
      

Error Reporting


<?php
// Report all errors
error_reporting(E_ALL);

// Turn off error reporting
error_reporting(0);

// Custom error handler
set_error_handler(function($errno, $errstr) {
  echo "Error: [$errno] $errstr";
});
?>
      
Back to Tutorials