我在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块,(就像在这种情况下一样),我该怎么办呢?
之前,我可以这样做吗?如果不是为什么?
答案 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){
}
尝试后必须立即抓住。这些是规则。