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?

All QuestionsCategory: Cpp LanguageWrite 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?
Chetan Shidling Staff asked 5 years ago

I need short information, can anyone explain.

1 Answers
Chetan Shidling Staff answered 5 years ago

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