re-throw an exception

This is a discussion on re-throw an exception within the C++ Programming forums, part of the General Programming Boards category; Yello. Quick question regarding re-throwing an exception. Many examples of re-throwing exceptions use code similar to that below. But they ...

  1. #1
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87

    re-throw an exception

    Yello.

    Quick question regarding re-throwing an exception.

    Many examples of re-throwing exceptions use code similar to that below. But they do NOT explain exactly why you want to do it.

    This code terminates the program with a debug error dialogue message from MSVC. Now, normally you probably wont rethrow from these circumstances - but this is similar to the simple examples found on the web and in books. Is the idea to terminate execution of the program at this point or what?

    Cheers

    FB
    Code:
    #include <iostream>
    
    using namespace std;
    
    class CError
    {
    private:
    	const char * error;
    public:
    	CError(const char * e) { error = e; }
    	void output() { cout << error << endl; }
    };
    
    void check(int num)
    {
    	if (num < 0)
    		throw CError("Negative Number");
    }
    
    int main(void)
    {
    	int x;
    
    	try
    	{
                    // Enter a negative number to
                    // throw the exception
    		cout << "Enter a positive number: " << flush;
    		cin >> x;
    		check(x);
    	}
    	catch(CError & e)
    	{
    		e.output();
    		throw; // Rethrow the exception
    	}
    
    	return 0;
    }
    Visual C++ .net
    Windows XP profesional

  2. #2
    Registered User kiss_psycho's Avatar
    Join Date
    Feb 2003
    Posts
    49
    if you are wanting to rethrow, make sure you catch the exception in an enclosing block. for this, better terminate the program execution at the said point instead of rethrowing to terminate.
    Definition of Programmer : A red-eyed mumbling mammal capable of conversing with inanimate objects.

    Happy Hunting...
    The Root

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    161
    But they do NOT explain exactly why you want to do it.
    Much of the time, this is used to clean up resources if an error occurs.

    For example, a project that I'm currently working on includes a recursive descent parser with a parse tree generator. If it spots an error, it throws an exception. My parser will catch the exception first, and clean up all the parse nodes, and then rethrow it so that the calling code can be notified.

  4. #4
    Registered User
    Join Date
    Jun 2003
    Posts
    245
    thefroggy: This is exactly how my code works also. The exception is caught by the first handler, which cleans up it's part of the resource, and then rethrows to the next handler so that it can also clean up it's resources, etc, all the way back to the primary (last-chance) exception handler.

  5. #5
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    That is definitely a good reason to catch and then re-throw an exception, and I do that in my code as well. However, I just wanted to point out that to my knowledge you should have the goal of programming so that resources are automatically cleaned up when an exception is thrown and they go out of scope.

    For example, I recently changed this code:
    Code:
    {
        MyObj* pMyObj = 0;
        try
        {
            pMyObj = new MyObj;
            pMyObj->DoSomethingThatMightThrow();
            pMyObj->DoSomethingElse();
            delete pMyObj;
        }
        catch (exception& )
        {
            delete pMyObj;
            throw;
        }
    }
    to this:
    Code:
    {
        std::auto_ptr<MyObj> pMyObj(new MyObj);
        pMyObj->DoSomethingThatMightThrow();
        pMyObj->DoSomethingElse();
    }
    Both do pretty much the same thing. Sometimes the cleanup is very different when an error has occurred versus normal destruction of the object, but when its not I think its good to try to avoid the extra work by having things clean themselves up.

  6. #6
    Registered User
    Join Date
    Jun 2003
    Posts
    245
    Not sure about MSVC++, but C++ Builder has a nice extension for this. It's called "__finally" :

    "The __finally keyword specifies actions that should be taken regardless of how the flow within the preceding __try exits."

    Using it in a "try/__finally" block, you can get code executed regardless of whether there way an exception in the middle or not, which means the cleanup code for error condition is exactly the same as success.

    However, since it's non-portable, I tend to not use this approach.

  7. #7
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87
    Thanks all, that has made it somewhat clearer.
    Visual C++ .net
    Windows XP profesional

  8. #8
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87
    Okay, i've got home and have been playing with this with a compiler.. and I reckon I have got it now with all your help.

    Yeah, so the problem I have been having is that I have not had an encompassing error handler. So when the function threw the exception it was caught by the handler, but when the exception was rethrown, there was no subsequent handler to catch the rethrown exception (because the rethrow unwinds the stack until the next handler is found) and thus it would call terminate() and bail out of the program.

    Otherwise the code that I gave for the first example bails out with an error. The following code allows one to recover from the failure and continue if appropriate.
    Code:
    try
    {
    // Do stuff
    	try
    	{
                    // Enter a negative number to
                    // throw the exception
    		cout << "Enter a positive number: " << flush;
    		cin >> x;
    		check(x); // Throws the exception of type CError if x is negative
    	}
    	catch(CError & e)
    	{
    		e.output();
    		throw; // Rethrow the exception
    	}
    }
    catch(...) // Just catch everything for this example
    {
       // See what can be done about the rethrow...
    }
    Of course the above code is not really meant to be functional just instructional.
    Last edited by filler_bunny; 10-15-2003 at 07:08 AM.
    Visual C++ .net
    Windows XP profesional

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lifetime of temporary during exception throw
    By brewbuck in forum C++ Programming
    Replies: 3
    Last Post: 05-22-2009, 05:08 PM
  2. STL sort throw exception?
    By George2 in forum C++ Programming
    Replies: 11
    Last Post: 01-10-2008, 06:34 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  4. Replies: 5
    Last Post: 06-07-2007, 12:10 AM
  5. std::bad_exception donīt throw exception
    By ripper079 in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2003, 07:47 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21