【发布时间】:2012-09-06 19:30:28
【问题描述】:
当我从类中调用函数时,我无法理解何时抛出和捕获异常。
请想象我的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?
什么是正确的做法?
救命!
【问题讨论】:
标签: php exception exception-handling custom-exceptions