當我從類中調用函數時,我無法得知自己的頭何時拋出並捕獲異常。處理一個類的函數的多個調用的例外
請想象一下,我QuizMaker
類看起來是這樣的:
// Define exceptions for use in class
private class CreateQuizException extends Exception {}
private class InsertQuizException extends Exception {}
class QuizMaker()
{
// Define the items in my quiz object
$quiz_id = null;
$quiz_name = null;
// Function to create a quiz record in the database
function CreateQuizInDatabase()
{
try
{
$create_quiz = // Code to insert quiz
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;
}
}
function InsertQuestions()
{
try
{
$insert_quiz = // Code to insert quiz
if (!$insert_quiz)
{
// There was an error creating record in the database
throw new CreateQuizException("Failed inserting quiz in to database");
}
else
{
// Success inserting quiz, return true
return true;
}
}
catch (InsertQuizException $insert_exception)
{
// Error inserting question
return false;
}
}
}
......並使用此代碼,我使用類數據庫
class QuizMakerException extends Exception {}
try
{
// Create a blank new quiz maker object
$quiz_object = new QuizMaker();
// Set the quiz non-question variables
$quiz_object->quiz_name = $_POST['quiz_name'];
$quiz_object->quiz_intro = $_POST['quiz_intro'];
//... and so on ...
// Create the quiz record in the database if it is not already set
$quiz_object->CreateQuizRecord();
// Insert the quiz in to the database
$quiz_object->InsertQuestions();
}
catch (QuizMakerException $quiz_maker_error)
{
// I want to handle any errors from these functions here
}
創建一個新的測驗
對於這段代碼,我想調用QuizMakerException
,如果任何函數不執行我想要的(當前它們返回TRUE或FALSE)。
什麼是正確當這段代碼中的任何函數沒有執行我所希望的任何功能時,會如何捕獲?目前他們只是返回TRUE或FALSE。
- 難道我真的有把大量的if/else語句的調用各功能之間,我認爲這是在異常的整點,他們只是停止的try/catch內進一步語句的執行?
- 我是否在我的函數的
catch
內拋出QuizMakerException?
什麼是正確的做法?
幫助!
我建議看看github上的一些代碼。搜索PHP項目並查看它們如何使用異常非常簡單。 Zend框架可能會提供一些很好的例子。 – ficuscr