Question

In: Computer Science

c++ Add exception handling to the MyStack class (e.g. an instance of the class should throw...

c++

Add exception handling to the MyStack class (e.g. an instance of the class should throw an exception if an attempt is made to remove a value from an empty stack) and use the MyStack class to measure the execution cost of throwing an exception. Create an empty stack and, within a loop, repeatedly execute the following try block:

try { i n t s t a c k . pop ( ) ;

} catch ( e x c e p ti o n& e ) { . . . }

Compare the execution time to the simpler statement that avoids the exception altogether.

i f ( ! i n t s t a c k . i s em p t y ( ) )

i n t s t a c k . pop ( ) ;

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//updated MyStack.hpp

#ifndef MyStack_H

#define MyStack_H

#include<vector>

#include<stdexcept>

template <typename T>

class MyStack{

                private:

                //using a vector as underlying data structure

                std::vector<T> stk;

                public:

                //adds an element to the top (back)

                void push(T element);

                //removes and returns the top element

                T pop();

                //returns the top element, without removing

                T top() const;

                //returns true if stack is empty

                bool empty() const;

                //returns the current number of elements

                int size() const;

};

//implementation of all methods

template <typename T>

void MyStack<T>::push(T element){

                //simply adding to the back

                stk.push_back(element);

}

template <typename T>

T MyStack<T>::pop(){

                //throwing exception if stack is empty

                if(empty()){

                                throw std::runtime_error("empty stack!");

                }

                //getting last element

                T element=stk[stk.size()-1];

                //removing it

                stk.pop_back();

                //returning it

                return element;

}

template <typename T>

T MyStack<T>::top() const{

                //throwing exception if stack is empty

                if(empty()){

                                throw std::runtime_error("empty stack!");

                }

                //getting and returning last element

                T element=stk[stk.size()-1];

                return element;

}

template <typename T>

bool MyStack<T>::empty() const{

                return stk.empty();

}

template <typename T>

int MyStack<T>::size() const{

                return stk.size();

}

#endif

//main.cpp (for comparing execution times)

#include <iostream>

#include<chrono>

#include "MyStack.hpp"

using namespace std;

using namespace std::chrono;

int main()

{

                //creating an empty stack

    MyStack<int> intstack;

                int loopCount=1000000;

                //recording start time

                auto start1 = high_resolution_clock::now();

                //looping for loopCount number of times

                for(int i=0;i<loopCount;i++){

                                //popping from stack, catching exception

                                try { intstack.pop() ;

                                }

                                catch ( exception& e) { }

                }

                //recording end time, and finding time difference in micro seconds

                auto stop1 = high_resolution_clock::now();

                auto time1 = duration_cast<microseconds>(stop1 - start1);

                //displaying result

                cout<<"Using try catch took "<<time1.count()<<" micro seconds to run a loop of "<<

                                loopCount<<" times"<<endl;

               

                //recording start time

                auto start2 = high_resolution_clock::now();

                //looping

                for(int i=0;i<loopCount;i++){

                                //checking if stack is empty before popping

                                if(!intstack.empty()){

                                               intstack.pop();

                                }

                }

                //recording end time and finding time taken

                auto stop2 = high_resolution_clock::now();

                auto time2 = duration_cast<microseconds>(stop2 - start2);

                //displaying result

                cout<<"Using statements avoiding excepions took "<<time2.count()<<

                " micro seconds to run a loop of "<< loopCount<<" times"<<endl;

                //Obviously, the second option is way faster than using try-catch

    return 0;

}

/*OUTPUT*/

Using try catch took 5020278 micro seconds to run a loop of 1000000 times

Using statements avoiding excepions took 38256 micro seconds to run a loop of 1000000 times


Related Solutions

in C#, What is an exception and what are the advantages of exception handling?
in C#, What is an exception and what are the advantages of exception handling? What are the differences between the traditional error-handling methods and the object-oriented exception-handling methods and when should you use each one? Provide three to four paragraphs detailing your findings/views on these questions..provide examples with a simple code also..
EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates...
EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates an exception class called ManyCharactersException, designed to be thrown when a string is discovered that has too many characters in it. Consider a program that takes in the last names of users. The driver class of the program reads the names (strings) from the user until the user enters "DONE". If a name is entered that has more than 20 characters, throw the exception....
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a  ...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to   be   thrown   when   a   string   is   discovered   that   has   too   many   characters   in   it. Consider   a   program   that   takes   in   the   last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,  ...
EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates  ...
EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to be thrown when a   string is discovered that has too many characters in it. Consider a   program that   takes   in the last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,   throw   the   exception.  ...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc or VS2017) when an input is invalid (i.e., no data, wrong format, wrong type, etc.) and fails the type conversion. Generate random integers from any of the following three non-overlapped ranges -14 ~ -7 -2 ~ 5 33 ~ 44 Numbers generated must also randomly distributed across the three ranges.
write in c++ Create a program that uses EXCEPTION HANDLING to deal with an invalid input...
write in c++ Create a program that uses EXCEPTION HANDLING to deal with an invalid input entry by a user. a. Write a program that prompts a user to enter a length in feet and inches. The length values must be positive integers. b. Calculate and output the equivalent measurement in centimeters 1 inch = 2.54 centimeters c. Write the code to handle the following exceptions: If the user enters a negative number, throw and catch an error that gives...
1. Implement the Vehicle class.  Add the following private instance variables to the Accoun class:...
1. Implement the Vehicle class.  Add the following private instance variables to the Accoun class: • An instance variable called wheelsCount of type int • An instance variable called vType of type String • An instance variable called isTruck of type boolean .  Add getters and setters for the three instance variables  Add the following methods to the Account class: • A void method called initialize that takes a parameter of type int, a String,and one double...
Apply JavaFX and exception handling to design a CircleApp class using proper JavaFX GUI components, such...
Apply JavaFX and exception handling to design a CircleApp class using proper JavaFX GUI components, such as labels, text fields and buttons(Submit, Clear, and Exit) to compute the area of circle and display the radius user entered in the text field and computing result in a proper location in the application windows. It will also verify invalid data entries for radius(No letters and must be a postive real number) using expection handling. Your code will also have a custom-designed exception...
Exception handling All Exceptions that can be thrown must descend from this Java class: The getMessage(...
Exception handling All Exceptions that can be thrown must descend from this Java class: The getMessage( ) method is inherited from this class? What are the two broad catagories of Exceptions in Java? If an Exception is not a checked exception it must extend what class? What is the difference between a checked Exception and an unchecked Exception? What are the two options a programmer has when writing code that may cause a checked Exception to be thrown? Can a...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try and catch" statement to catch an exception if "empStatus == 1" hourly wage is not between $15.00/hr. and $25.00/hr. The keywords “throw” and “throws” MUST be used correctly and both keywords can be used either in a constructor or in a method. If an exception is thrown, the program code should prompt the user for the valid input and read it in. *NOTE*- I...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT