In php , why it is used "new" when reporting an exception since we do not need a variable cause action is already being concluded. This is a code i found when learning exception handling. I am having trouble understanding this.
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>
Can't we use
throw Exception('Division by zero.');
An Exception is an instance of the Exception class. If there is no instance of this class already created, then we have to create it. Since Errors are handled through non-static classes, we can't use it as a static method.