8

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?

0

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Be aware of set_error_handler() can't handle Fatal Errors as said @hakre in his answer.
7

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.

1 Comment

You can catch PHP Errors this way, but you need to enable it.
7

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.