2011-09-27 40 views
0

雖然在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 ++編譯器是扔...

[email protected]:~/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’ 
+1

除了'從字符串常量「字符*」不贊成使用轉換'也是一個重要的警示。確保你使用'const char *'作爲字符串文字。 – iammilind

回答

3

你不能有一個catch沒有try。放行:

try { 

之前while聲明。

如果您想擺脫關於字符串常量的警告,您可能必須將類型更改爲const char *或明確地轉換/複製它們。或者您可以使用-Wno-write-strings選項gcc

4

您需要圍繞代碼try {...}構造,否則catch將不知道它應該捕獲什麼代碼。

包裝你while循環到try

try { 
while(1) 
    { 
    ..... 
    }// end of while(1) 
} catch(UnderFlowException e) ... 

Reference

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; 
} 
從答案,