这是try-catch-finally的可接受的用法吗?
问题描述:
基本上我正在寻找一些澄清,这将是一个可以接受的尝试使用,终于抓住?基于它的电子邮件和用户名是唯一的一张表这是try-catch-finally的可接受的用法吗?
try
{
$db = new Database;
$success = ["message" => "Please check your Email address to activate your account"];
$process = $db->prepare('INSERT INTO users (username, email, password, profileImg, profileImgPath, profileImgType, accountStatus, verified, joined)
VALUES
(:username, :email, :password, :filename, :filepath, :filetype, :activationCode, 0, NOW())');
$process->bindValue(':username', $username);
$process->bindValue(':email', $email);
$process->bindValue(':password', password_hash($post['password'], PASSWORD_DEFAULT));
$process->bindValue(':activationCode', $activationCode);
$process->bindValue(':filename', $filename);
$process->bindValue(':filepath', $filepath);
$process->bindValue(':filetype', $filetype);
$process->execute();
$code = 'https://gotsocial.co.uk/gotsocial/active.php?activecode=' . $activationCode . '.
';
$to = $post['email'];
$subject = 'GOT Social';
$from = "[email protected]";
$result = mail($to, $subject, $code, "From: $from");
}
catch(Exception $e)
{
$errors[] = ["name" => "username", "error" => "Username may already be taken"];
}
catch(Exception $e)
{
$errors[] = ["name" => "email", "error" => "Email may already be registered"];
}
finally
{
header("refresh:10; url=index.php");
}
答
不,你不能有相同的catch(Exception $e)
两次。你有,如果你需要有不同的抓否则必须将它们合并到一个
try
{
$db = new Database;
$success = ["message" => "Please check your Email address to activate your account"];
$process = $db->prepare('INSERT INTO users (username, email, password, profileImg, profileImgPath, profileImgType, accountStatus, verified, joined)
VALUES
(:username, :email, :password, :filename, :filepath, :filetype, :activationCode, 0, NOW())');
$process->bindValue(':username', $username);
$process->bindValue(':email', $email);
$process->bindValue(':password', password_hash($post['password'], PASSWORD_DEFAULT));
$process->bindValue(':activationCode', $activationCode);
$process->bindValue(':filename', $filename);
$process->bindValue(':filepath', $filepath);
$process->bindValue(':filetype', $filetype);
$process->execute();
$code = 'https://gotsocial.co.uk/gotsocial/active.php?activecode=' . $activationCode . '.
';
$to = $post['email'];
$subject = 'GOT Social';
$from = "[email protected]";
$result = mail($to, $subject, $code, "From: $from");
}
catch(Exception $e)
{
$errors[] = ["name" => "username", "error" => "Username may already be taken"];
$errors[] = ["name" => "email", "error" => "Email may already be registered"];
}
finally
{
header("refresh:10; url=index.php");
}
这是有道理的改变异常的类型,得益于 我会接受的答案,当计时器倒计数 – cakeman
没有担心蛋糕师 – SMH