我只是第一次在我的代碼中實現異常。哪裏可以定義異常類
對於在類函數中使用的異常,哪裏最好定義異常?
這裏有一個類,代表了一段代碼,我已經寫了幾個功能:
//
// Do I define my exception here?
//
class CreateQuizException extends Exception {}
class Quiz()
{
// Define the items in my quiz object
$quiz_id = null;
$quiz_name = null;
// Function to create a quiz record in the database
function CreateQuizInDatabase()
{
//
// OR DO I DEFINE IT WITHIN THE FUNCTION??
//
class CreateQuizException extends Exception {}
try
{
// Insert the record in to the database
$create_quiz = mysql_query("INSERT INTO quizzes (quiz_name) VALUES ("' . $this->quiz_name . '")");
if (!$create_quiz)
{
// There was an error creating record in the database
throw new CreateQuizException("Failed inserting record");
}
else
{
// Return true, the quiz was created successfully
return true;
}
}
catch (CreateQuizException $create_quiz_exception)
{
// There was an error creating the quiz in the database
return false;
}
catch (Exception $other_exception)
{
// There was another error
}
}
}
它是:該異常將被用於
- 以前類定義在
- 只有在之內它將被用於的功能
- 或者我還沒有想到的其他地方?
謝謝,這真的清除了一個。關於它的細節太細緻(這個例外名稱讓我笑,大聲btw!) – Luke
@Coulton如果你有兩個不同的錯誤條件可能會發生,你會使用不同類型的異常。從Java中獲取此示例:您有一個FileNotFound異常,其中找不到該文件,或者IOException,IO遇到問題。在你的示例代碼中,沒有任何東西可以產生一個異常(mysql_ *函數,除了被棄用,不使用異常),所以你會很好依靠內置的異常。 – nickb
您可以在PHP中將類定義爲私有的其他類嗎? – Diego