Skip to content

Teaching Notes: Module 05

  • Exception handling (try/catch/throw)
  • Custom exception classes
  • Nested exception classes
  • Exception-safe design

  • Grade 1 = highest, 150 = lowest
  • Increment = grade goes DOWN (more senior)
  • Throw exceptions for invalid grades
  1. Grade logic backwards

    void Bureaucrat::incrementGrade() {
    _grade++; // WRONG - increment means better = lower number
    _grade--; // CORRECT
    }
  2. Exception class not inheriting std::exception

    class GradeTooHighException : public std::exception {
    const char* what() const throw() {
    return "Grade is too high";
    }
    };
  3. Not making name const

    • const std::string _name; - can’t change after construction

  • Form has grades required to sign AND execute
  • Bureaucrat signs Form, Form validates grade
  1. Checking wrong direction

    // Remember: lower number = better
    if (bureaucrat.getGrade() > _gradeToSign)
    throw GradeTooLowException();
  2. signForm() output format

    • Success: <name> signed <form>
    • Failure: <name> couldn't sign <form> because <reason>

  • Form -> AForm (abstract)
  • Add execute(Bureaucrat const&) const
  • Concrete forms: Shrubbery, Robotomy, Presidential
  1. Form must be signed
  2. Executor grade must be high enough
  • “Where should execution requirements be checked - base or derived?”
  • “Why might it be better to check in the base class?”

AForm* Intern::makeForm(const std::string& name, const std::string& target) {
// Use function pointers or map, NOT if/else forest
}
  1. Using if/else chain

    • Subject explicitly forbids this
    • Use array of function pointers
  2. Memory management

    • Intern creates form, caller must delete
typedef AForm* (*FormCreator)(const std::string&);
AForm* createShrubbery(const std::string& t) {
return new ShrubberyCreationForm(t);
}
// ... other creators ...
AForm* Intern::makeForm(const std::string& name, const std::string& target) {
std::string names[] = {"shrubbery creation", "robotomy request", "presidential pardon"};
FormCreator creators[] = {createShrubbery, createRobotomy, createPresidential};
for (int i = 0; i < 3; i++) {
if (name == names[i]) {
std::cout << "Intern creates " << name << std::endl;
return creators[i](target);
}
}
std::cerr << "Form not found: " << name << std::endl;
return NULL;
}