Write a program that reads two integers from the standard input and prints the result of dividing the first number by the second. Revise your program to throw an exception if the second number is zero. Test your program with a zero input to see what happens on your system if you don’t catch an exception. Revise your program from the previous exercise to use a try block to catch the exception. The catch clause should print a message to the user and ask them to supply a new number and repeat the code inside the try.


First at all, we’ll define the insertion of the numbers from cin:



Then we’re gonna use the try block where we’ll put the expressions that may throw an exception:

      if(!i2){ //intepreting the int number as a boolean type
            throw invalid_argument("Denominator mustn't be 0 (zero)");

Finally we define catch clauses where we should ask the user to insert another valid number; if the user inserts another invalid number again, then the program throws another exception.

In this level, the program requests the user to decide if he/she wants to continue with the program; if the answer is Y (or any other than ‘n’) then the program calls itself recursively; if not, it finishes the execution.

catch(invalid_argument err){
            cout<<"Type another number other that zero"<<endl;
                    throw invalid_argument("Denominator mustn't be 0");
            catch(invalid_argument err1){
                cout<<"You have type two incorrect number, "
                      "Want to continue Y/n?"<<endl;
                char c;

At the end of the function, there are sentences that can’t throw an exception:




Lippman, S. B., Lajoie, J., & Moo, B. E. (2015). C Primer. Upper Saddle River, NJ: Addison-Wesley.

Leave a Reply

Your email address will not be published.