Mut*_*han 1 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++;
}
}
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误:
错误:'我'之前的预期'捕获'
我认为这个问题出现了,因为我没有写下try块下面的catch块.但是如果想在main()中编写catch块,(就像在这种情况下),我怎么能这样做?
以前,我可以这样做吗?如果不是为什么?
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
}
Run Code Online (Sandbox Code Playgroud)