我只是第一次在我的代码中实现异常。
对于在类函数中使用的异常,哪里最好定义异常?
这是一个类和一些函数,它们代表我编写的一段代码:
//
// Do I define my exception here?
//
class CreateQuizException extends Exception {}
class Quiz()
{
// Define the items in my quiz object
$quiz_id = null;
$quiz_name = null;
// Function to create a quiz record in the database
function CreateQuizInDatabase()
{
//
// OR DO I DEFINE IT WITHIN THE FUNCTION??
//
class CreateQuizException extends Exception {}
try
{
// Insert the record in to the database
$create_quiz = mysql_query("INSERT INTO quizzes (quiz_name) VALUES ("' . $this->quiz_name . '")");
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;
}
catch (Exception $other_exception)
{
// There was another error
}
}
}
是吗:
- 在将使用异常的类定义之前
- 仅在将要使用的函数内
- 还是我没有想到的其他地方?