在使用try-catch in时,遇到了这个错误。但是,尽管我上网和SO,我还是找不出这个错误的原因。
我的代码是...
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.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;
}
对我来说,上面代码中的一切似乎都是正确的。但是g++编译器抛出了.
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’
发布于 2011-09-27 09:41:58
如果没有try
,就不能有catch
。放入下面这行:
try {
在您的while
语句之前。
如果您希望摆脱有关字符串常量的警告,则可能必须将类型更改为const char *
或显式强制转换/复制它们。或者,您可以使用gcc
的-Wno-write-strings
选项。
发布于 2011-09-27 09:47:24
您需要将代码包含在try {...}
构造中,否则catch
将不知道它应该捕获哪些代码。
将while
循环包装到try
中
try {
while(1)
{
.....
}// end of while(1)
} catch(UnderFlowException e) ...
发布于 2011-09-27 18:35:09
试试这个:
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;
}
https://stackoverflow.com/questions/7563319
复制相似问题