Hi experts!
I'm learning C++. I wish to write a C++ program with exception handling.
Please give a simple program for divisor by zero using C++.
And detail syntax for defining exception.
Error handling in C++?
Unlike Java, C++ does not have a standard exception for divide-by-zero so you have to build your own. Many, arguably all, exceptions in c++ should be derived from the standard exceptions in, oddly enough, the stdexcept header file. Since this is a runtime error this example derives from std::runtime_error.
This should help you get started but it is obviously not a complete treatment of the topic of exceptions. You should read more on your own.
#include %26lt;iostream%26gt;
#include %26lt;exception%26gt;
#include %26lt;stdexcept%26gt;
using namespace std;
class DivideByZeroException : public runtime_error
{
public:
DivideByZeroException() : runtime_error("attempt to divide by zero" ) {}
};
int main()
{
int num;
int dem;
int res;
cout %26lt;%26lt; "Enter numerator: ";
cin %26gt;%26gt; num;
cout %26lt;%26lt; "Enter denominator: ";
cin %26gt;%26gt; dem;
try
{
if (dem == 0)
{
throw DivideByZeroException();
}
res = num / dem;
cout %26lt;%26lt; "Result = " %26lt;%26lt; res %26lt;%26lt; endl;
}
catch (DivideByZeroException %26amp;e)
{
cout %26lt;%26lt; "Exception: " %26lt;%26lt; e.what() %26lt;%26lt; endl;
}
return(0);
}
Reply:#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
#include%26lt;iostream.h%26gt;
void main()
{
int a,b,c;
cin%26gt;%26gt;a;
cin%26gt;%26gt;b;
try
{
if(b==0)
throw(1);
}
catch(int)
{
cout%26lt;%26lt;"divide error";
}
getch();
}
Reply:use try and catch block. keep the code that causes exception in try block n the code for handling error in catch block.
try{
int i = 5/0;
}
catch(Exception e){ // well this is java code but still c++ code is similar
// handle
}
augustifolia
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment