void main(){
int x=5;
int y=0;
try{
cout%26lt;%26lt;x/y;
}
catch{
cout%26lt;%26lt;"cannot devide by zero";
}
}
//the problem is the catch block
Correct this c++ code?
try - C++ keyword that denotes an exception block (You had this correct)
catch - C++ keyword that "catches" exceptions (you needed to add the variable type parameter)
throw - C++ keyword that "throws" exceptions (You needed to put a throw statement in to activate if you were "dividing by zero"
EDIT: I initialized the divide variable to zero, the program works fine when I compile it, try re-building the solution, if it still doesn't work, I'd have to take a look at what compiler your using (which you didn't mention) to find out what the problem is. OR at least describe your error. Regardless I doubt your compiler would reject integer division, which is the only thing I could think of at the current time that would cause a crash, but I haven't used every compiler yet.
EDIT: I did a minor rewrite of the program, try it now.
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
int x=5;
int y=0;
int divide;
try
{
x/y;
throw 1;
}
catch(int a)
{
cout%26lt;%26lt;"cannot devide by zero" %26lt;%26lt; endl;
system("pause");
return 1;
}
divide = x / y;
cout %26lt;%26lt; divide;
system("pause");
return 0;
}
Reply:I think you might try to put the paranthesis () at the end of the catch before braces{...}
Try it and have a good luck.
Reply:You need to tell C++ ,the type of exception that you want to catch. This is done as follows :
try{
/** Your try code block goes here */
}
catch(Exception e){
/** Your catch code block goes here */
}
Here Exception is the base exception class(superclass).
Try this, it should work.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment