Portekoi
Portekoi

Reputation: 1157

Exception not catch by Try/Catch in PHP

i've try this example :

<?php    
try {
    Not_Exist();
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
?>

http://php.net/manual/en/language.exceptions.php But the error is not catched :

Fatal error: Call to undefined function Not_Exist() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\mysite\public_html\exception.php on line 3

Why? I'm usually using Dotnet. Maybe i miss something.

Upvotes: 0

Views: 581

Answers (3)

binaryatrocity
binaryatrocity

Reputation: 976

Because that is a fatal error, not an exception. You're going to want to use PHP's function_exists() method and try something like:

try{
    function_exists(Not_Exist);
} catch (Exception $e) {
    // error here
}
// run Not_Exist here because we know its a valid function.

Upvotes: 2

gordoncarroll
gordoncarroll

Reputation: 106

There is no Exception being thrown in your code. You're simply hitting a fatal error. If you're trying to find a way around fatal errors, this post may be of help. How do I catch a PHP Fatal Error

If you're trying to catch Exceptions, something like this:

try {
   throw new Exception("Exception Message");
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Upvotes: 2

Marc B
Marc B

Reputation: 360862

error is not an exception. PHP itself doesn't throw exceptions on syntax errors, such as missing functions. You'd need set_error_handler() to "catch" such things - and even then, a custom error handler can't handle parse errors such as this.

Upvotes: 5

Related Questions