What are some differences between error and exception in PHP?
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.
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.
"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.
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.
精彩评论