クラスから関数を呼び出すときに例外をスローしてキャッチするときに頭を悩ませることはできません。
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
は、関数のいずれかが目的の機能を実行しない場合にaを呼び出します(現時点では、TRUEまたはFALSEを返します)。
このコードの関数のいずれかが私が望むことを実行しない場合にキャッチするための正しい方法は何ですか?現時点では、単にTRUEまたはFALSEを返します。
- 各関数の呼び出しの間に本当にたくさんのif/elseステートメントを配置する必要がありますか?それが例外の要点だと思いました、それらは単にtry / catch内のさらなるステートメントの実行を停止しますか?
- 関数内からQuizMakerExceptionをスローし
catch
ますか?
正しいことは何ですか?
ヘルプ!