Question

12.5 Program: Divide by Zero (C++) This program will test exception handling during division. The user...

12.5 Program: Divide by Zero (C++)

This program will test exception handling during division.

The user will enter 2 numbers and attempt to divide (in a try block) the 1st number by the 2nd number.

The program will provide for 2 different catch statements:

Division by zero - denominator is zero

Division results in a negative number

The user should be prompted with Enter 2 numbers:

For input of 7 and 0 the output should be Exception: Division by zero

For input of 7 and 2 the output should be a/b = 3.5

For input of 7 and -2 the output should be Exception: Division is negative

L

Lab Submission

12.5.1: Program: Divide by Zero

Instructions

Deliverables

DivideByZero.cpp

We will expect the above file(s) to be submitted

Compile command

g++ DivideByZero.cpp -Wall -o a.out

We will use this command to compile your code

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Exceptions are runtime errors that a program encounters during execution.

Exception handling mechanism is used which identifies and deal with such condition. Exception handling mechanism consists of following parts:

Find the problem (Hit the exception)
Inform about its occurrence (Throw the exception)
Receive error information (Catch the exception)
Take proper action (Handle the exception)

3 keywords for handling the exception in c++ language. They are

  1. try: Try block consists of the code that may generate exception. Exception are thrown from inside the try block.
  2. throw: Throw keyword is used to throw an exception encountered inside try block. After the exception is thrown, the control is transferred to catch block.
  3. catch: Catch block catches the exception thrown by throw statement from try block. Then, exception are handled inside catch block.

Syntax

try

{

    statements;

    ... ... ...

    throw exception;

}

catch (type argument)

{

    statements;

    ... ... ...

}

Multiple catch exception

Multiple catch exception statements are used when a user wants to handle different exceptions differently. For this, a user must include catch statements with different declaration.

Syntax

try
{
    body of try block
}

catch (type1 argument1)
{
    statements;
    ... ... ...
}

catch (type2 argument2)
{
    statements;
    ... ... ...
}
... ... ...
... ... ...
catch (typeN argumentN)
{
    statements;
    ... ... ...
}

Program code:

#include <iostream>

using namespace std;

int main() //tesitng for program

{

    int a,b; //Declare the variables

    cout << "Enter 2 numbers: ";

    cin >> a >> b;

    try

    {

        if (b != 0)

        {

            float div = (float)a/b;

            if (div < 0)

                throw 'e';

            cout << "a/b = " << div;

        }

        else

            throw b;

           

    }

    catch (int e)

    { //exception1

        cout << "Exception: Division by zero"<<endl;

    }

  

    catch(...) //exception2

    { // it can catch all those exception which are not handled by other catch statements.

        cout << "Exception: Division is negative"<<endl;

    }

    return 0;

}

output is:

Example1:

sh-4.2$ g+ -o main *.cpp sh-4.2$ main Enter 2 numbers: 7 0 Exception: Division by zero

Example2:

Default Term Browser sh-4.2$ g++ -o main *.cpp sh-4.2$ main Enter 2 numbers 7 2 a/b 3.5

Example3:

sh-4.2$ g++ -o main .cpp sh-4.2$ main Enter 2 numbers: 7 2 Exception: Division is negative sh-4.2$

Add a comment
Know the answer?
Add Answer to:
12.5 Program: Divide by Zero (C++) This program will test exception handling during division. The user...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Division by Zero Problem: Create a program titled Division. Have the program prompt the user "Enter...

    Division by Zero Problem: Create a program titled Division. Have the program prompt the user "Enter numerator and denominator" and store the two values entered. (If you wish the user to "Enter numerator/denominator" be sure to adjust your data gathering variables to include a holder variable for the slash character.) Include a function titled Quotient that takes 2 integers as input and provides the quotient of the 2 integers as integer output. (The remainder is truncated. Thus, 5/3 will be...

  • C++ Your assignment this week is to make your fractionType class safe by using exception handling....

    C++ Your assignment this week is to make your fractionType class safe by using exception handling. Use exceptions so that your program handles the exceptions division by zero and invalid input. · An example of invalid input would be entering a fraction such as 7 / 0 or 6 / a · An example of division by zero would be: 1 / 2 / 0 / 3 Use a custom Exception class called fractionException. The class must inherit from exception...

  • Please help I am confused to where start. It C++ program thank you The stoi function...

    Please help I am confused to where start. It C++ program thank you The stoi function converts a string to an integer, but does not check whether or not the value of the string is a good integer. If the stoi function fails, an exception is thrown and the program terminates. Write a program that asks the user to enter two strings, one called sNumerator and the other sDenominator. Using the stoi function, convert the two strings to numbers but...

  • (C programing, Not C++) Write a program in C that asks the user to input 10...

    (C programing, Not C++) Write a program in C that asks the user to input 10 numbers. Store these numbers in an array. Then ask the user to input a single number. Your program should execute a linear search on the array, trying to find that number. If the number exists in the array, have the program print out which position/element the number was found at. If the target number is not in the array, have the program print out...

  • Write an assembler program that asks the user (as shown below) for two integers and a...

    Write an assembler program that asks the user (as shown below) for two integers and a single character representing the arithmetic operations: addition, subtraction, multiplication and integer division (displays both quotient and remainder). Perform the requested operation on the operands and display the result as specified below. Assume SIGNED NUMBERS. The program should not divide by 0! If the user attempts to divide by 0, display the error message: "Cannot divide by zero." If this error occurs, the program should...

  • PLEASE I NEED C# Objectives Learn the basics of exception handling. Background Exceptions are essentially unexpected...

    PLEASE I NEED C# Objectives Learn the basics of exception handling. Background Exceptions are essentially unexpected situations. It is difficult to write a program that can handle all possible situations, as we have found out through the many programs we have written. For example, should your program accept accidental input? Does it use the metric system or the empirical system? Do users of your program know which system it uses? In order to deal with all these possibilities, exceptions were...

  • C Program: Trap divide by zero. Write a main (include libraries as always) that asks the...

    C Program: Trap divide by zero. Write a main (include libraries as always) that asks the user to enter two numbers(up to 100 times). For each pair of numbers divide the first number by the second and print the result. Set up and use the signal handler to trap the divide by zero, give the user a pleasant greeting before exiting. Test with no zeroes before forcing the error by entering zero for the second number

  • Creating a Calculator Program

    Design a calculator program that will add, subtract, multiply, or divide two numbers input by a user.Your program should contain the following:-The main menu of your program is to continue to prompt the user for an arithmetic choice until the user enters a sentinel value to quit the calculatorprogram.-When the user chooses an arithmetic operation (i.e. addition) the operation is to continue to be performed (i.e. prompting the user for each number, displayingthe result, prompting the user to add two...

  • You must write a C program that prompts the user for two numbers (no command line...

    You must write a C program that prompts the user for two numbers (no command line input) and multiplies them together using “a la russe” multiplication. The program must display your banner logo as part of a prompt to the user. The valid range of values is 0 to 6000. You may assume that the user will always enter numerical decimal format values. Your program should check this numerical range (including checking for negative numbers) and reprompt the user for...

  • USING PYTHON *Write a program, in which the user enters two numbers, then divides the first...

    USING PYTHON *Write a program, in which the user enters two numbers, then divides the first number by the second, and prints the result to two decimal places. *Make sure that that the inputs are floats (with exception handling using the ValueError). *Make sure that there is no divide by zero error (with exception handling). *Then have a plain exception: That handles any other error. -Thank you in advance for your assistance-

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT