Php 您如何看待在catch中嵌套try/catch语句?
你觉得这篇作文怎么样?错了吗?如何做好这件事Php 您如何看待在catch中嵌套try/catch语句?,php,exception,try-catch,Php,Exception,Try Catch,你觉得这篇作文怎么样?错了吗?如何做好这件事 $graph_url = 'https://graph.facebook.com/me?access_token=' . $result['access_token']; $fb_user = json_decode( file_get_contents( $graph_url ) ); try { $user = new Model_User( $fb_user->username ); $user_meta = new Mo
$graph_url = 'https://graph.facebook.com/me?access_token=' . $result['access_token'];
$fb_user = json_decode( file_get_contents( $graph_url ) );
try {
$user = new Model_User( $fb_user->username );
$user_meta = new Model_User_Meta ( $user->get ( 'user_id' ) );
$user_meta->set_user_meta( '_facebook_id', $fb_user->id );
$user_meta->set_user_meta( '_last_logged_in', 'current_timestamp' );
$user_meta->save();
} catch ( Exception $e ) {
if ( $e->getCode() === 0 ){
$password = Helper_Password::generate_password();
$hash = Helper_Password::hash_string( $password );
try {
$user = new Model_User();
$user->set( 'user_name', $fb_user->username );
$user->set( 'user_pass', $hash );
$user->set( 'user_email', $fb_user->email );
$user->set( 'user_status',( $fb_user->verified ? 'active' : 'inactive' ) );
$user->set( 'display_name', $fb_user->name );
$status = $user->save();
$user_meta = new Model_User_Meta ( $status->user_id );
$user_meta->set_user_meta( '_facebook_id', $fb_user->id );
$user_meta->set_user_meta( '_last_logged_in', 'current_timestamp' );
$user_meta->save();
} catch ( Exception $e ) {
throw $e;
}
} else {
throw $e;
}
}
在捕获过程中尝试恢复,然后在必要时抛出异常是可以的 但是这里的代码有一些模糊性。你想扔哪个
$e
?原始异常,还是新异常?如果要引发原始异常,则不应在第二个catch语句中重写$e
:
} catch ( Exception $e ) {
if ( $e->getCode() === 0 ){
try {
// try recovering here?
} catch ( Exception $otherException ) {
throw $e; // throw the original exception instead of the new one
}
} else {
throw $e;
}
}
如果要抛出新异常,则根本不需要内部捕获
} catch ( Exception $e ) {
if ( $e->getCode() === 0 ){
// try recovering here, and let the exception fly as they will
} else {
throw $e;
}
}
在捕获过程中尝试恢复,然后在必要时抛出异常是可以的 但是这里的代码有一些模糊性。你想扔哪个
$e
?原始异常,还是新异常?如果要引发原始异常,则不应在第二个catch语句中重写$e
:
} catch ( Exception $e ) {
if ( $e->getCode() === 0 ){
try {
// try recovering here?
} catch ( Exception $otherException ) {
throw $e; // throw the original exception instead of the new one
}
} else {
throw $e;
}
}
如果要抛出新异常,则根本不需要内部捕获
} catch ( Exception $e ) {
if ( $e->getCode() === 0 ){
// try recovering here, and let the exception fly as they will
} else {
throw $e;
}
}
这样可以吗?可能值得留下一个链接为什么会被问到这个问题,这可能比仅仅建议另一个网站更有帮助:这样可以吗?可能值得留下一个链接为什么会被问到这个问题,这可能比仅仅建议另一个网站更有帮助: