开发者

Try-Catch Problem in c++

开发者 https://www.devze.com 2023-04-09 02:29 出处:网络
I am trying queue implementation in c++. During that I am having this problem. void Queue::view() { int i;

I am trying queue implementation in c++. During that I am having this problem.

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++;
 }
}

This gives an error as :

error: expected ‘catch’ before ‘i’

I think this problem is arises since I doesn't written cat开发者_JAVA百科ch block below try block. But If want to write the catch block in main(), ( like in this case ), how could I do that?

Before, that Could I do that? If not Why?


catch block must follow the try block. If you want the catch to be in main - that's where the try has to be too. You can throw everywhere, doesn't have to be inside a try block within the same function.

It should be something like this:

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
}


You simply need to remove the try block. A try block always goes with a 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]<<" ";
}

You can then include a try/catch construct in your main.

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


All try blocks need at least one associated catch block. You should remove the try block if you have no intentions of handling any exceptions here. Exceptions can be (and usually should be!) thrown outside of a try block.


Make your code catch and rethrow the exception, like this:

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

Although you don't even need the try block in the first place. Looks like just throw ex; would work, since you don't intend to catch it but just throw it.


try{
}
catch(Exception ex){
}

Catch must be immediately after try. These are the rules.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号