在try-catch中工作时遇到了这个错误。但我无法找出这个错误的原因,虽然我上网并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’
答案 0 :(得分:4)
如果没有catch
,您就无法拥有try
。放线:
try {
在您的while
声明之前。
如果你想摆脱有关字符串常量的警告,你可能需要将类型更改为const char *
或显式地转换/复制它们。或者您可以使用-Wno-write-strings
选项gcc
。
答案 1 :(得分:4)
您需要在try {...}
构造中包含您的代码,否则catch
将无法知道它应捕获的代码。
将while
循环换入try
:
try {
while(1)
{
.....
}// end of while(1)
} catch(UnderFlowException e) ...
答案 2 :(得分:0)
试试这个:
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;
}