Reputation: 3307
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 catch 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?
Upvotes: 1
Views: 5794
Reputation: 20282
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
}
Upvotes: 7
Reputation: 613592
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;
}
Upvotes: 3
Reputation: 26940
try{
}
catch(Exception ex){
}
Catch must be immediately after try. These are the rules.
Upvotes: 0
Reputation: 81409
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.
Upvotes: 0
Reputation: 2487
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.
Upvotes: 1