4

I'm a beginner in PHP. So far, from the source I'm learning from, the only mechanism to trigger an exception is by writing a line that throws it.

throw new Exception('message')

Furthermore, on the code below, any exception won't be thrown, but an error will be raised.

try
{
    $file = fopen('no such file.txt', 'r');
}
catch(Exception $e)
{
    echo 'Exception: ' . $e->getMessage();
}

Please give me some explanations. It seems this try..catch block is not so useful in PHP, unlike in Java or .NET.

3 Answers 3

4

By convention, the functions in the PHP core do not throw exceptions (the only exception is that constructors may throw exceptions, because there's no other way for them to properly signal error conditions).

Some differences:

  • Exceptions have types, and you can catch them according to their type. Errors only have an associated level (E_WARNING, E_STRICT, E_NOTICE, ...).
  • Exceptions can be caught at any point in the call stack, otherwise they go to a default exception handler. Errors can only be handled in the defined error handler.
Sign up to request clarification or add additional context in comments.

Comments

3

"errors" are remains from the pre-oop era of php and are indeed hardly useful in the modern code. Fortunately, you can (actually, must) automatically convert most "errors" to exceptions. The magic is like this

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

Once you've got this, your "fopen" snippet will work as expected. See http://php.net/manual/en/class.errorexception.php for more details/discussion.

Comments

0

It is not useful in this specific case, because fopen() doesn't throw an exception when it encounters an error. I think none of the core functions do.

If you are used to working with exceptions and want to work consistently with them, I think there is nothing speaking against using the ErrorException class to turn all errors into exceptions.

However, fopen() throws only a E_WARNING when it fails to open a file, so in your example, it would be easiest to test whether $file is false to see whether the operation failed.

I personally also like to do a file_exists() before fopen(), and react accordingly if the file is missing.

2 Comments

I have some reservations as to your last advice. It's OK for local files, but if the file is actually a http url, for instance, this causes more delay that simply checking the return value of fopen and, god forgive me, suppress the error messages (which can be obtained with error_get_last()).
@Artefacto For http URLs, I agree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.