当我从类中调用函数时,我无法理解何时抛出和捕获异常。
请想象我的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),我想调用 a。
当此代码中的任何函数未执行我想要的操作时,捕获的正确方法是什么?目前他们只是返回 TRUE 或 FALSE。
- 我真的必须在调用每个函数之间放置大量 if/else 语句吗,我认为这就是异常的全部意义所在,它们只是停止在 try/catch 中执行进一步的语句?
- 我是否从
catch
我的函数中抛出 QuizMakerException?
什么是正确的做法?
帮助!