c ++中的Try-Catch问题

时间:2011-09-26 19:47:25

标签: c++ exception-handling try-catch

我在c ++中尝试队列实现。在此期间我遇到了这个问题。

void Queue::view() 
{
 int i;
 try
 {
  if(Qstatus==EMPTY)
  {
    UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
    throw ex;
  }
 }

 i=front;
 cout<<"Queue contains...\n";

 while(i <= rear)
 {
  cout<<queue[i]<<" ";
  i++;
 }
}

这会产生错误:

  

错误:在'i'之前预期'捕获'

我认为这个问题出现了,因为我没有写下try块下面的catch块。 但是如果想在main()中编写catch块,(就像在这种情况下一样),我该怎么办呢?

  

之前,我可以这样做吗?如果不是为什么?

5 个答案:

答案 0 :(得分:7)

catch块必须遵循try块。如果您希望catch位于main - 这也是try所必须的位置。您可以在任何地方throw,不必在同一功能中的try块内。

它应该是这样的:

void Queue::view() 
{
 int i;
 if(Qstatus==EMPTY)
 {
    UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
    throw ex;
 }

 i=front;
 cout<<"Queue contains...\n";

 while(i <= rear)
  cout<<queue[i]<<" ";
}
/// ...
int main()
{
    Queue q;
    try{
       q.view();
    }
    catch(UnderFlowException ex)
    {
        /// handle
    }
    catch (...)
    {
     /// unexpected exceptions
    }
    // follow the success/handled errors
}

答案 1 :(得分:3)

您只需删除try块即可。 try块始终带有catch

void Queue::view() 
{
    int i;
    if(Qstatus==EMPTY)
    {
        ex = UnderFlowException("\nQUEUE IS EMPTY");
        throw ex;
    }

    i=front;
    cout<<"Queue contains...\n";

    while(i <= rear)
        cout<<queue[i]<<" ";
}

然后,您可以在try/catch中添加main个构造。

int main()
{
    Queue queue;
    try
    {
        queue.View()
    }
    catch(UnderFlowException ex)
    {
        //handle ex
    }
    return 0;
}

答案 2 :(得分:1)

所有try块至少需要一个关联的catch块。如果您无意在此处理任何异常,则应删除try块。例外可以(并且通常应该!)抛出try块之外。

答案 3 :(得分:0)

让代码捕获并重新抛出异常,如下所示:

try
{
 if(Qstatus==EMPTY)
 {
   UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
   throw ex;
 }
} catch( ... ) {
   throw; // rethrow whatever exception we just catched
}

虽然您首先不需要try块。看起来只有throw ex;会起作用,因为你不打算抓住它而只是抛出它。

答案 4 :(得分:0)

try{
}
catch(Exception ex){
}

尝试后必须立即抓住。这些是规则。