当我从类中调用函数时,我无法得知自己的头何时抛出并捕获异常。处理一个类的函数的多个调用的例外
请想象一下,我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