12.5 Program: Divide by Zero (C++) This program will test exception handling dur
ID: 3812756 • Letter: 1
Question
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
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
Explanation / Answer
DivideByZero.cpp
#include<iostream>
using namespace std;
int main()
{
int a,b; // declarations of integer variables
float c,d; // declarations of float variables
try // try block to check the numbers whether throw exception or not
{
cout<<"enter the two numbers"<<endl;
cin>>a>>b; // reading two integers
if(b>0) // contion tocheck denominotor greter than 0
{
c=(float)a/b; // casting integer value to float value
cout<<"a/b="<<c<<endl;
}
else if(b==0)
{
throw b;// raising exception
}
else if(b<0)
{
d=a/b;
throw d;
}
}
catch(int) // catching divide by zero exception
{
cout<<"Division by zero"<<endl;
}
catch(float j) // catching division by negative exception
{
cout<<"Division by Negative"<<endl;
}
return 0;
}
output:
**************************************
Test Case1:
sh-4.2$g++ DivideByZero.cpp -Wall -o a.out
enter the two numbers 7 0
Division by zero
***************************************
Test Case2:
sh-4.2$ g++ DivideByZero.cpp -Wall -o a.out
enter the two numbers
7 -2
Division by Negative
****************************************
Test Case3:
sh-4.2$ g++ DivideByZero.cpp -Wall -o a.out
enter the two numbers 7 2
a/b=3.5
*****************************************
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.