KodeFor.Me
KodeFor.Me

Reputation: 13511

PHP try catch exceptions

Hello I have a code like that :

try
{
    // Here I call my external function
    do_some_work()
}
catch(Exception $e){}

The question is: If the do_some_work() has a problem and produce an Error this try catch will hide the error?

Upvotes: 8

Views: 19450

Answers (3)

Spudley
Spudley

Reputation: 168655

There are two types of error in PHP. There are exceptions, and there are errors.

try..catch will handle exceptions, but it will not handle errors.

In order to catch PHP errors, you need to use the set_error_handler() function.

One way to simplify things mught be to get set_error_handler() to throw an exception when you encounter an error. You'd need to tread carefully if you do this, as it has the potential to cause all kinds of trouble, but it would be a way to get try..catch to work with all PHP's errors.

Upvotes: 12

hakre
hakre

Reputation: 197554

produce a Fatal Error

No, catch can not catch Fatal Errors. You can not even with an error handler.

If you want to catch all other errors, have a look for ErrorException and it's dedicated use with set_error_handler:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();

Upvotes: 7

Sjoerd
Sjoerd

Reputation: 75568

If do_some_work() throws an exception, it will be catched and ignored.

The try/catch construct has no effect on standard PHP errors, only on exceptions.

Upvotes: 7

Related Questions