I’m just implementing Exceptions in to my code for the first time.
For exceptions that are used within a class function, where is best to define the exception?
Here’s a class and a few functions that represent a piece of code that I have written:
//
// 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
}
}
}
Is it:
- Before the class definition that the exception will be used in
- Only Within the function that it will be used in
- Or somewhere else that I haven’t thought of?
Typically I’ve seen and used two places for Exception placement for two distinct reasons:
Outside of the class definition, since is it possible that the Exception will be thrown to the caller and I want to be explicit that this Exception is in the public namespace. It might be useful to note that I really only see Exceptions placed at the end of the class file in which they’re defined, but this is preference and has no functional significance.
Inside of the class definition, but outside of the method definitions, if the Exception is local to this class, not relevant outside of the class, and not going to be handled by the caller. Typically, the
privateaccess modifier is introduced to enforce this.However, I do not believe that PHP supports nested classes, as I cannot get one example of nested classes to parse. I am drawing my examples more from Java than PHP.
Placing Exception definitions inside methods seems too granular, you’ll end up polluting your code with Exceptions and end up with: