一个完整的例子,因为问题应该有一个可接受的答案:
在构造函数中抛出异常,如下所示:
class SomeObject {
public function __construct( $allIsGoingWrong ) {
if( $allIsGoingWrong ) {
throw new Exception( "Oh no, all is going wrong! Abort!" );
}
}
}
然后在创建对象时,捕获如下错误:
try {
$object = new SomeObject(true);
// if you get here, all is fine and you can use $object
}
catch( Exception $e ) {
// if you get here, something went terribly wrong.
// also, $object is undefined because the object was not created
}
如果由于某种原因您没有在任何地方捕获错误,它将导致致命异常,这将导致整个页面崩溃,这将解释您“未能捕获异常”并将向您显示消息.