What is this error in the code?
while working in try-catch in came across this error. But I cant trace out the reason for this error though I surfed the net and SO.
My code is...
int main()
{
Queue q;
int choice,data;
while(1)
{
choice = getUserOption();
switch(choice)
{
case 1:
cout<<"\nEnter an element:";
cin>>data;
q.enqueue(data);
break;
case 2:
int element;
element = q.dequeue();
cout<<"Element Dequeued:\n"<<element;
break;
case 3:
q.vi开发者_如何学Goew();
break;
case 4:
exit(EXIT_SUCCESS);
}
catch(UnderFlowException e)
{
cout<<e.display();
}
catch(OverFlowException e)
{
cout<<e.display();
}
}// end of while(1)
return 0;
}
For me everything in the above code seems to be correct. But g++ complier is throwing...
muthu@muthu-G31M-ES2L:~/LangFiles/cppfiles/2ndYearLabException$ g++ ExceptionHandlingEdited.cpp
ExceptionHandlingEdited.cpp: In member function ‘void Queue::enqueue(int)’:
ExceptionHandlingEdited.cpp:89:97: warning: deprecated conversion from string constant to ‘char*’
ExceptionHandlingEdited.cpp: In member function ‘int Queue::dequeue()’:
ExceptionHandlingEdited.cpp:113:95: warning: deprecated conversion from string constant to ‘char*’
ExceptionHandlingEdited.cpp: In member function ‘void Queue::view()’:
ExceptionHandlingEdited.cpp:140:66: warning: deprecated conversion from string constant to ‘char*’
ExceptionHandlingEdited.cpp: In function ‘int main()’:
ExceptionHandlingEdited.cpp:185:3: error: expected primary-expression before ‘catch’
ExceptionHandlingEdited.cpp:185:3: error: expected ‘;’ before ‘catch’
ExceptionHandlingEdited.cpp:189:3: error: expected primary-expression before ‘catch’
ExceptionHandlingEdited.cpp:189:3: error: expected ‘;’ before ‘catch’
You can't have a catch
without a try
. Put the line:
try {
before your while
statement.
If you want to get rid of the warnings about the string constants, you'll probably have to change the types to const char *
or explicitly cast/copy them. Or you can use the -Wno-write-strings
option to gcc
.
You need to surround your code in try {...}
construct, otherwise catch
will not know what code it should catch.
Wrap your while
loop into try
:
try {
while(1)
{
.....
}// end of while(1)
} catch(UnderFlowException e) ...
Reference.
Try this:
int main()
{
Queue q;
int choice,data;
while(1)
{
choice = getUserOption();
try
{
switch(choice)
{
case 1:
cout<<"\nEnter an element:";
cin>>data;
q.enqueue(data);
break;
case 2:
int element;
element = q.dequeue();
cout<<"Element Dequeued:\n"<<element;
break;
case 3:
q.view();
break;
case 4:
exit(EXIT_SUCCESS);
}
}
catch(UnderFlowException e)
{
cout<<e.display();
}
catch(OverFlowException e)
{
cout<<e.display();
}
}// end of while(1)
return 0;
}
精彩评论