PHP allows handling traditional runtime errors and object-oriented exceptions together using a unified approach. By converting errors into exceptions, developers can manage all failures through structured try-catch blocks.
set_error_handler().A custom error handler transforms PHP errors into ErrorException objects. Once registered, all errors behave like exceptions and can be caught inside try-catch blocks.
// Convert PHP errors into exceptions
<?php
function errorToException($severity,$message,$file,$line){
throw new ErrorException($message,0,$severity,$file,$line);
}
// Register custom error handler
set_error_handler("errorToException");
try{
// Trigger a PHP error
$number=5/0;
// Manually throw an exception
throw new Exception("Manual exception triggered");
}
catch(ErrorException $ee){
echo "Caught an error as exception: ".$ee->getMessage()."<br>";
}
catch(Exception $e){
echo "Caught an exception: ".$e->getMessage()."<br>";
}
?>
Both runtime errors and manual exceptions are captured using catch blocks. PHP notices such as division by zero are treated the same way as traditional exceptions.
Think of the process as:
@.