我无法理解何时抛出和捕获异常,当我从类中调用函数时。
请想象一下我的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
}
对于这段代码,如果任何一个函数没有执行我想要的操作(目前它们返回TRUE或FALSE),我希望调用“QuizMakerException”。如何正确地捕获此代码中任何函数没有执行我想要的操作的情况?目前它们只返回TRUE或FALSE。
您是否真的需要在调用每个函数之间放置许多if/else语句?我认为这就是异常的全部意义,它们仅仅停止try/catch中进一步语句的执行。
我应该从我的函数的catch中抛出QuizMakerException吗?
什么是正确的做法?
帮帮我!