Method 2 - ExceptionsPros: Automatic cleanup and elegant shutdown, opportunity to continue if handled, works in both debug and release builds Cons: Relatively slow ExplanationBasically, you use the throw keyword to throw data up to some unknown function caller and the stack continues to unwind (think of it like the program is reversing itself) until someone catches the data. You use the try keyword to enclose code that you'd like to catch exceptions from. See: void some_function() { throw 5; } // some function that throws an exception int main(int argc, char* argv[]) { try // just letting the compiler know we want to catch any exceptions from this code { some_function(); } catch(const int x) // if the type matches the data thrown, we execute this code { // do something about the exception... } } If you don't place try blocks in your code, then the stack will simply continue to unwind until it gets past the main function, and your program will exit. You don't have to place them everywhere - only where you can catch an exception and can recover from it. If you can only recover from it partially, you can rethrow the original exception (by the empty throw statement "throw;") and the stack will continue unwinding until it hits the next matching catch block. ExamplesExceptions are best used in key places in debug and release builds to track exceptional conditions. If used properly, they provide automatic cleanup and then either force the application to quit or put itself back into a valid state. Thus exceptions are perfect for release code, because they provide everything the end user wants in a well-behaved program that encounters unexpected errors. Correctly used, they provide the following benefits:
Because of the overhead, it is generally a bad idea to use them for normal flow control because other control structures will be faster and more efficient.
|