Exceptions

From Vaddina.com

Jump to: navigation, search

Exceptions Vs.Return values

The program execution does not terminate unless explicitly stated.
try and catch The good old return

Constructors and destructors does not return values. Moreover they naturally throw exceptions. Hence ignoring this and trying to accomplish something with error codes is not quite advisible.

Cannot be used, in their original sense, in Constructors and Destructors. However, the constructors and destructors can be passed references or pointers, or a member variable can be used to save the result of an operation.

They can be used over function boundaries. Thus when a function raises an exception, it can be handled anywhere in the parent functions where the function in question is called.

Example

void fn1()
{
     cout << “function – 1<< endl;
     try { fn2(); }    
     catch(int i)
     {cout << “ exception “ << I; }
     cout << “In function – 1.1;
}

void fn2()
{
 cout << “In function – 2<< endl;
 fn3();
 cout << “In function – 2.2;
}

void fn3()
{
     cout << “In function – 3;
     throw 3;
     cout << “In function – 3.3;
}
 
int main()
{
    fn1();
    cout << “I am in Main” << endl;
}

Such a technique is not possible. The parent function which called the error generating function must handle the exception, based on the returned error code.

One of the primary use of exception handling with tryand catch is explained in the following example.

// Class storing information of an exception
class CException
{
public:
   char* message;
   CException(char* m) { message = m };
   Report();
}

try{
CalculateValue();
SetValue();
GetValue();
}

catch (CException &ce)
{ ce.Report(); }

In the example above we can observe that any exceptions of the type CException thrown by three functions can be caught by a single catch block. Such type of mechanism eventhough possible to implement using simple return codes, may need several if statements, which is often hard to read and maintain.

The program execution does not terminate unless explicitly stated.

Personal tools
Namespaces
Variants
Actions
Navigation
My Work
C/C++
Tutorials/Books/eBooks
Miscelleneous
Contact
Other
Toolbox