Question

In: Computer Science

Not sure where to begin on this c++ assignment. The instructions are to enclose the current...

Not sure where to begin on this c++ assignment. The instructions are to enclose the current contents of the print_output function into a try block that throws two different exceptions based on which line catches the bad input (shape or color). You will then print an appropriate message based on the type of exception that was thrown.

this is what I have so far:

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <iostream>


namespace color {
       enum color{
         red   = 0xFF0000,
       green = 0x00FF00,
       blue = 0x0000FF,
       white = 0x000000

};
}
namespace shape {
       enum shape{
         circle = 0,
       triangle = 1,
       square = 2
};
}
void print_object(int color, int shape) {

   int r = color >> 16 & 0xFF;
   int g = (color >> 8) & 0xFF;
   int b = color & 0xFF;

   color::color estimated_color = color::white;

   if ( (r > g) and (r > b) ) {
       estimated_color = color::red;
   }
   else if ( (g > r) and (g > b) ) {
       estimated_color = color::green;
   }
   else if ( (b > r) and (b> g) ) {
       estimated_color = color::blue;
   }
   std::cout<<"The object is a ";
   switch ( estimated_color ) {
   case color::red: std::cout<<"red "; break;
   case color::green: std::cout<<"green "; break;
   case color::blue: std::cout<<"blue "; break;
   default: exit(1);
   }

   switch ( shape ) {
   case shape::triangle: std::cout<<"triangle";break;
   case shape::square: std::cout<<"square "; break;
   case shape::circle: std::cout<<"circle "; break;
   default: exit(1);
   }
   std::cout<<std::endl;
}
int main() {
   int random_color = 0;
   int random_shape = 0;
   srand(time(NULL));
   print_object(color::red, shape::circle);
   print_object(color::green, shape::square);
   print_object(color::blue, shape::square);
   for (int i=0; i < 10; i++) {
       random_color = rand() % 0xFFFFFF;
       random_shape = rand() % 3;
       print_object(random_color, random_shape);
   }
   return (0);
}

Solutions

Expert Solution

Exception Handling:

Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution.

There are two types of exceptions: a)Synchronous, b)Asynchronous

C++ provides following specialized keywords and blocks to handle these exceptions.

try: represents a block of code that can throw an exception.

catch: represents a block of code that is executed when a particular exception is thrown.

throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.

// Modified source code to handle exceptions raised with bad input of color and shape

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <iostream>

namespace color {
enum color{
red = 0xFF0000,
green = 0x00FF00,
blue = 0x0000FF,
white = 0x000000

};
}
namespace shape {
enum shape{
circle = 0,
triangle = 1,
square = 2
};
}

void print_object(int color, int shape) {
  
// try block

try
{
   int r = color >> 16 & 0xFF;
int g = (color >> 8) & 0xFF;
int b = color & 0xFF;

color::color estimated_color = color::white;

if ( (r > g) and (r > b) ) {
estimated_color = color::red;
}
else if ( (g > r) and (g > b) ) {
estimated_color = color::green;
}
else if ( (b > r) and (b> g) ) {
estimated_color = color::blue;
}

std::cout<<"The object is a ";
switch ( estimated_color ) {
case color::red: std::cout<<"red "; break;
case color::green: std::cout<<"green "; break;
case color::blue: std::cout<<"blue "; break;
default: throw 'c'; // throws Exception if color is not blue, red or green
//default: exit(1);
}

switch ( shape ) {
case shape::triangle: std::cout<<"triangle";break;
case shape::square: std::cout<<"square "; break;
case shape::circle: std::cout<<"circle "; break;
default: throw 's'; // throws Exception if shape is not triangle, square or circle.
//default: exit(1);
}
  
std::cout<<std::endl;
}

//catch block
catch(char ch) // Catches exception
{
if (ch=='c') // displays color exception
std::cout<<"Bad Input: Color exception"<<std::endl;
else
if(ch=='s') // displays shape exception
std::cout<<"Bad Input: Shape exception"<<std::endl;
}

}

int main() {
int random_color = 0;
int random_shape = 0;
srand(time(NULL));
  
print_object(color::red, shape::circle);
print_object(color::green, shape::square);
print_object(color::blue, shape::square);
for (int i=0; i < 10; i++) {
random_color = rand() % 0xFFFFFF;
random_shape = rand() % 3;
print_object(random_color, random_shape);
}
  return (0);
}

You can check this program by

changing the statement in main() function

random_shape = rand() % 3; to

random_shape = rand() % 5; i.e change number 3 to more than 3 .

It raises shape exception.

Similarly, you can also change estimated_color value and can raise color exception.


Related Solutions

Respond to the following prompt to complete the CTE assignment. Be sure to follow the instructions...
Respond to the following prompt to complete the CTE assignment. Be sure to follow the instructions in the syllabus and your grade will be determined through the use of the related rubric (also located in the syllabus). As the Baby Boom generation continues to retire from the labor force, the ratio of retirees to workers will continue to increase. How will this demographic change impact the Social Security program? What "solution" or "solutions" would best offset the harmful effects of...
I am not sure where, to begin with, this problem... "You have found the following historical...
I am not sure where, to begin with, this problem... "You have found the following historical information for DEF Company:                          Year1       Year 2        Year 3        Year 4 Stock Price        $46.29         $49.74          $54.55          $57.07 EPS                  $2.04 $2.9    $2.81    $3.78 Earnings are expected to grow at 8 percent for the next year. Using the company's historical average PE as a benchmark, what is the target stock price in one year?"
Python: I am not sure where to begin with this question, and I hope I can...
Python: I am not sure where to begin with this question, and I hope I can get an input on it. This is in regards to Downey's program, and we are asked to make two changes. Downey prints time as they do in the Army: 17:30:00 hours. We want to print that as 5:30 PM. Downey lets you define the time 25:00:00 - we want to turn over at 23:59:59 to 00:00:00. (I am asked to identify my changes with...
Program Assignment 1 C++ please Instructions This assignment will require the use of three arrays, which...
Program Assignment 1 C++ please Instructions This assignment will require the use of three arrays, which will be used in parallel. Create a program that keeps track of the sales of BBQ sauces for a company. The company makes several different types of sauces, Original, Sticky Sweet, Spicy, Sweet Heat, Hickory Bourbon and Smokey Mesquite. One array will contain the names of the different BBQ sauces. This array will be initialized from a text file with the 6 different names....
Instructions: The assignment is based on the mini case below. The instructions relating to the assignment...
Instructions: The assignment is based on the mini case below. The instructions relating to the assignment are at the end of the case. Katie Holmes and Sam Wilson are facing an important decision. After having discussed different financial scenarios into the wee hours of the morning, the two computer engineers felt it was time to finalize their cash flow projections and move to the next stage – decide which of two possible projects they should undertake. Both had a bachelor...
This is for an accounting assignment and I'm not sure where I'm going wrong. I'll copy...
This is for an accounting assignment and I'm not sure where I'm going wrong. I'll copy and paste what I have and the directions as best as possible. PLEEEASE HELP: June 22: Received a bill for $1,190 from Computer Parts and Repair Co. for repairs to the computer equipment. It's telling me my rep and maintenance expense is wrong. I entered: Repairs & Maint. Expense 1190 Accounts payable 1190 It's for Byte of Accouting. What else would this transaction be...
**CODED IN C LANGUAGE** Case 1: The given snapshot in the assignment instructions checks for the...
**CODED IN C LANGUAGE** Case 1: The given snapshot in the assignment instructions checks for the following: P to be switched with Q (Once done will remain as it is in all the rows) If the user enters the same P again, the program must not make any changes For instance, given elements are 0123456789 3 4          0              0124456789 2 5          1              0154456789 (Keeping the change in Row 0 (input for row 1); 2 is switched to 5) 1 6          2              0654456789 (Keeping...
Instructions for C++ project This Assignment will Focus on Software Engineering: Using Functions in a Menu...
Instructions for C++ project This Assignment will Focus on Software Engineering: Using Functions in a Menu Driven Program Hint: Chapter 6 Program 6-10 is a great example of this type of programs. Your Task: Write a calculator Program with following functions (lack of function will result in a grade of zero). Your program must have the following menu and depending on the users choice, your program should be calling the pertaining function to display the result for the user. 1...
Instructions Find an article that describes a current oligopoly market. Be sure and cite your reference(just...
Instructions Find an article that describes a current oligopoly market. Be sure and cite your reference(just the URL) so others can read the full article. Briefly discuss any of the following items that you find evident in this market: high concentration ratios, collusion, price-fixing, price leadership, heavy non-price competition, interdependence among firms, barriers to entry, anti-trust problems
THIS ASSIGNMENT MUST BE DONE IN C++ 17 AND MUST FOLLOW EACH GUIDELINE LISTED BELOW. INSTRUCTIONS...
THIS ASSIGNMENT MUST BE DONE IN C++ 17 AND MUST FOLLOW EACH GUIDELINE LISTED BELOW. INSTRUCTIONS START HERE: Our satisfied clients are back to ask us to implement another interactive dictionary. Our dictionary takes input from users and uses the input as search key to look up values associated with the key. Requirements: - Coding: No hard coding - Data Source: a text file, Data.CS.SFSU.txt - Data Structure: Use existing data structure(s) or create new data structure(s) to store our...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT