Jor*_*sen 4 php exception-handling try-catch
我需要捕获函数"包含"PHP的最后一个错误.
我测试了"Exceptions"函数,但不幸的是我已经在函数"include"上面写了.
如果我在函数"include"之后写,则不显示异常.
例1:
try{
throw new exception();
require_once( $this->controller['path'] );
}
catch( exception $e )
{
print_r( error_get_last() );
}
Run Code Online (Sandbox Code Playgroud)
这个回归: ...(无效)......
例2:
try{
require_once( $this->controller['path'] ) OR throw new exception();;
}
catch( exception $e )
{
print_r( error_get_last() );
}
Run Code Online (Sandbox Code Playgroud)
此返回:解析错误:语法错误,意外T_THROW在......
我故意在要包含的文件中创建语法错误.想法是捕获错误,以便您可以调试它们.
任何人都知道如何得到这个?
伙计们!我需要捕获语法错误.问候!
首先,如果你使用require,如果不能包含文件,它总是会杀死你的应用程序.对结果无法控制,之后你无法做任何事情.如果要控制文件包含的成功,请使用include并测试其返回值.
$success = include "foo.php";
if (!$success) {
// the file could not be included, oh noes!
}
Run Code Online (Sandbox Code Playgroud)
你可以在语法上有所区别:
if (!(include "foo.php")) ...
Run Code Online (Sandbox Code Playgroud)
这将触发一个E_NOTICEif文件无法包含,你无法捕获.但这没关系,因为它可以帮助您调试问题,无论如何都会在生产中关闭错误显示(对,对吗?).
or throw new Exception不起作用,因为它throw是一个语句,不能在预期表达式的地方使用.
如果要捕获包含文件中的语法错误,请使用php_check_syntax/它的后继php -l <file>.
require_once 是一种语言结构,而不是一种功能,你不能与之短路.
要在包含文件之前测试文件是否存在,您可以使用is_file().如果要测试文件是否可读,可以使用is_readable().
如果找不到文件include,您可能还想使用哪个问题E_WARNING,而不是a E_COMPILE_ERROR.