Hi,
I need to know how to continue execution of code after throwing an exception. Has it got to do with where I place the throw statement?

Thanks in advance.

Recommended Answers

All 3 Replies

Exception handling is typically approached using a try catch statement, as demonstrated below:

#include <iostream>
using namespace std;
int main() {
   
   try {
    //your code here
   }
   catch( (datatype) e) {
      cout << "Exception raised: " << e<< '\n';
   //if the previous code had some sort of error that was associated
   //with (datatype)
   }
}

A try catch statement is like an if then statement, but it runs based off of errors instead. Basically, the computer will try to execute code in the try block. If it doesn't work, the computer will execute the code in the catch block. After executing code from either the try or the catch block the computer will run the rest of the code as normal.

You can have multiple try catch blocks in any function. Where the code says (datatype) in the above example is any data type that would cause the throwing of an exception. The throw statement causes the compiler to skip the try block and run the code in the highest nested catch block.

continue program exception in the catch block.

void foo()
{
    cout << "foo() is throwing an excetption\n";
    throw 1;
}

int main()
{
    try
    {
        foo();
    }
    catch(...)
    {
        cout << "Exception caught\n";
    }
    cout << "Ending program\n";
}

Output is this:

foo() is throwing an excetption
Exception caught
Ending program
Press any key to continue . . .

[edit]And what ^^^ said. He beat me to it. Oh well, that happens sometimes.[/edit]

Thanks for your help guys.

Much appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.