Write a C++ program to perform the following operation: A function to read two numbers from keyword. A function to calculate the division of these two numbers. A try block to throw an exception when a wrong type of data is keyed in. A try block to detect and throw an exception if the condition "divide-by-zero" occurs. Appropriate catch blocks to handle the exceptions thrown?
1 Answers
Code:
#include <iostream>
using namespace std;
int main()
{
float a,b;
cout<<“Enter values of a and b \n”;
cin>> a;
cin >> b;
float x = a-b;
try
{
if(x !=0 )
{
cout<<“Result (a/x) = ” << a/x << “\n”;
}
else
{
throw(x);
}
}
catch(float i)
{
cout<<“Exception caught : DIVIDE BY ZERO”;
}
cout<<“\nEND” << endl;
return 0;
}
Output:
Enter values of a and b
12
10
Result (a/x) = 6
END
Enter values of a and b
10
10
Exception caught: DIVIDE BY ZERO
END