2012-09-06 3 views
1

클래스에서 함수를 호출 할 때 예외를 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합니까?

옳은 일은 무엇입니까?

도움말!

답변

2

음은 일반적으로 예외를 throw 기능에, 당신이 그들을 던지거나에 "버블"발생 사람들을 수 있도록하려면, 당신 InsertQuestions 방법은 어떤 예외를 포착하지 않으려는 말한다. 그런 다음 "컨트롤러"코드는 예외를 처리하는 방법을 결정할 수 있습니다.

여기에 목표가 있다면 CreateQuizRecord이 실패하면 CreateQuizRecordInsertQuestions을 각각의 try 블록으로 줄 것입니다.

예외의 한 가지 이점은 간단한 bool 통과/실패 이상의 것을 알 수 있다는 점입니다. 기본 예외를 "Invalid_Paramter"와 같은 것으로 확장하고 특정 예외를 테스트하거나 예외 속성에서 이상적으로 추론하지 않습니다. catch 블록을 중첩하여 예외를 개별적으로 처리 할 수 ​​있습니다.

내 함수의 catch 내에서 QuizMakerException을 throw합니까?

예. 일반적으로 // Code to insert quiz 아래의 코드는 자체가 예외를 반환합니다. 모델 삽입에 실패한 경우 데이터베이스 예외가 발생할 수 있다고 가정합니다. 어떤 경우에는 데이터베이스 예외를 일으키게하거나, 지금 일종의 일을 수행하고 다른 예외를 던지기 만하면됩니다 (예외적으로 예외를 던지기도합니다).

각 함수를 호출하는 사이에 많은 if/else 문을 넣어야합니까? 예외의 전체적인 부분이라고 생각했지만 try/catch 내의 추가 문의 실행을 중지 시켰습니까?

내가 이런 식으로 보면, 예외를 throw이 하나가 예외를 던지는에 따라 달라집니다 후속 호출 다음 각 호출은, try 블록에 싸여되어야한다. 예외를 정상적으로 처리하려고한다고 가정하면 예외를 처리하고 중단하기 만하면됩니다. 오류 및 스택 추적이 표시됩니다. 때로는 바람직합니다.

+0

github에서 일부 코드를 살펴 보시기 바랍니다. PHP 프로젝트를 검색하고 예외를 사용하는 방법을 보는 것은 매우 쉽습니다. 젠드 프레임 워크 (Zend Framework)가 좋은 예가 될 수 있습니다. – ficuscr

0

가장 좋은 방법은 처음부터 예외를 삼가는 것이 아니라는 것입니다. 프로그램이 충돌하고 잘못된 출력을 처리하지 못하면 예외가 throw됩니다. 함수가 아무 것도 반환하지 않는 경우 (예외가 있더라도) 예외가 필요하지 않습니다.

질문에 대답하려면 if/elses를 많이 사용해야하는 경우 사용해야합니다.

2

구조를 약간 변경하고자 할 수 있습니다. 클래스 QuizMaker가 될 수 있습니다 : 올바르게 레코드를 삽입 할 수없는 경우

<?php 

// Define exceptions for use in class 
public class CreateQuizException extends Exception {} 
public 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 (Exception $create_quiz_exception) 
     { 
      // There was an error creating the quiz in the database 
      throw new CreateQuizException(
       "Failed inserting record " . 
       $create_quiz_exception->getMessage() 
      ); 
     } 
    } 

    function InsertQuestions() 
    { 
     try 
     { 
      $insert_quiz = // Code to insert quiz 

      if (!$insert_quiz) 
      { 
       // There was an error creating record in the database 
       throw new InsertQuizException("Failed inserting quiz in to database"); 
      } 
      else 
      { 
       // Success inserting quiz, return true 
       return true; 
      } 
     } 
     catch (Exception $insert_exception) 
     { 
      // Error inserting question 
      throw new InsertQuizException(
       "Failed inserting quiz in to database " . 
       $create_quiz_exception->getMessage() 
      ); 
     } 
    } 
} 

효과적으로, 당신이 삽입 예외를 throw합니다. 해당 코드 블록에 문제가 발생하면 catch하고 다시 삽입 예외를 throw합니다. Create 함수 (또는 가질 수있는 다른 함수)도 마찬가지입니다. 코드의 주요 블록에서

당신은 할 수 있습니다 :

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 (InsertQuizException $insert_exception) 
{ 
    // Insert error 
} 
catch (CreateQuizException $create_quiz_exception) 
{ 
    // Create error 
} 
catch (Exception $quiz_maker_error) 
{ 
    // Any other error 
} 

당신이 거기에 여러 catch 블록을하지 않으려면, 그냥 유형을 체크 한 후 하나를 캐치 (예외)를 유지하고 거기에서 취해지는 동작을 지정하기 위해서 슬로우되는 각 예외의 이름.

는 HTH

관련 문제