클래스에서 함수를 호출 할 때 예외를 throw하고 catch 할 때 주위에 머리를 쓸 수 없습니다.클래스의 함수를 여러 번 호출 할 때 예외 처리
내 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를 반환합니다.
- 난 정말 각 함수를 호출 사이에/경우 다른 문을 많이 넣어야 할 합니까, 나는 그들이 단순히 시도/캐치 내에서 더 명령문의 실행을 중지, 그 예외의 요점이라고 생각?
- 내 기능 중
catch
에서 QuizMakerException을 throw합니까?
옳은 일은 무엇입니까?
도움말!
github에서 일부 코드를 살펴 보시기 바랍니다. PHP 프로젝트를 검색하고 예외를 사용하는 방법을 보는 것은 매우 쉽습니다. 젠드 프레임 워크 (Zend Framework)가 좋은 예가 될 수 있습니다. – ficuscr