Reputation: 23801
I'm a php newbie so this might sound trivial Here is my php code
<?php
try
{
echo "Hello";
}
catch (Exception $e)
{
echo $e;
}
?>
This outputs Hello
Now i modified the code to get an exception
<?php
try
{
ech "Hello";
}
catch (Exception $e)
{
echo $e;
}
?>
But it prints nothing. Isn't the catch supposed to print the error.Or am i doing some thing wrong
Upvotes: 0
Views: 3778
Reputation: 12535
What you are looking for is ErrorException
.
You can register error handler like this:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
And catch errors:
try
{
echo $a; //Use of undefined variable
}
catch (ErrorException $e)
{
echo $e->getMessage();
}
But you can't handle syntax errors as exceptions neither in php nor in any other language. The reason why you get fatal error when php script actually runs is that php is interpreted. If you tried to compile your php script with any of php compilers, you'd get syntax error at compile-time.
If you want add some logging or something similar when fatal error occurs that you can register shutdown function (using register_shutdown_function
):
register_shutdown_function( "MyShutDownHandler" );
function MyShutDownHandler() {
//Do something here.
}
Upvotes: 5
Reputation: 9910
I would like to add one more thing to the great answers given by @PLB and @fab.
To catch an exception it needs to be thrown (kind of makes sense doesn't it? :P).
One example I quite like is handling division by 0.
function divide($x, $y) {
if ($y == 0) {
$up = new Exception('Cannot divide by 0');
throw $up; // :)
}
return $x/$y;
}
try {
divide(3, 0);
// more code can be added here, but is skipped if Exception is thrown.
} catch(Exception $e) {
echo $e->getMessage();
}
So why is this an improvement to an if
statement in the function?
For one, you don't need to manually skip the code between throw
and catch
. You can have your own exceptions(with some custom functionality, maybe log them if you want), and they are passed automatically through the call stack until they are caught.
Upvotes: 0
Reputation: 24551
No, this is a syntax error (or parse error in PHP terms). The code never gets executed in the first place, so no exceptions can be thrown.
It should also be noted that the PHP core functions do not throw exceptions neither because exceptions got introduced with PHP 5 and they did not remove the old error system. So now you have to deal with errors (core, old extensions) and exceptions (new OO extensions, userland code) simultaneously. You can partially avoid this with the ErrorException
(see example on linked manual page) but it's still a pain.
Upvotes: 2