Solved

Why use exceptions?

Posted on 1999-01-20
13
166 Views
Last Modified: 2010-04-02
I have been writing in C++ casually for a couple of years now and I have never really needed to use exceptions outside of constructors.

I am interested in hearing the reasons why a programmer would opt to use exceptions more liberally, if not exclusively.  Can anyone help with this?

Also, I've had some difficulty finding a tutorial on the net that outlines the moral use of exceptions.  I'm very interested in links and/or pointers if anyone has them.

Thanks,
cheeseburger
0
Comment
Question by:cheeseburger
  • 6
  • 4
  • 2
  • +1
13 Comments
 

Author Comment

by:cheeseburger
ID: 1184578
Adjusted points to 200
0
 
LVL 4

Accepted Solution

by:
pellep earned 200 total points
ID: 1184579
one pro is (in my opinion) that if you have several classmembers throwing the same exception and later in your program you call some of them, you can catch all of them in one try-block.

try {
myclass.myfunc1;
myclass.myfunc2;
myclass.myfunc3;
}
catch(myexception e) {
}

this makes errorhandling easier since you can specify all error-specific data in the exception. in java, for example, exceptions are used widely for error-handling. as for moral... no one can see your code once compiled. the most important thing is that
all possible exceptions are indeed caught and handeled.
also, several mfc-classes throws different exceptions.
and you can catch them all with 'catch(...)'. practical.

0
 
LVL 22

Expert Comment

by:nietod
ID: 1184580
1.  Exceptions keep the close clean by not clutering it with error handling code.  Without exceptions code tends to involve returning and managing error codes (Lots of if()s).  This gets to be a pain when the code gets heavily nested.  Often this also means that procedures cannot return ordinary non-error related return values because they must return return values.

continues.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184581
pellep beat me to it,   in short  it also helps insure that errors are handled at a site at which they can be knowledgably handled--often a problen with errror codes.  It tends to logicaly seperate ordinary processing code from errir handling code, which makes the code easier to read and maintain.   It provides a better mechnism for reporting errors, as any data needed in the reporting can be passed (try that with an error code).  Its cost is very minimal, specially compared to any tecnhique that tries to duplicate its power,
0
 
LVL 11

Expert Comment

by:alexo
ID: 1184582
Exceptions also take care of unwinding the stack (and destroying local objects) for you.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184583
But in C++ other error handling schemes, like use of error codes,  will also do that.  (Except, I guess, just terminating the program at the point there is a problem.  I'm not sure that counts, though.)
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 11

Expert Comment

by:alexo
ID: 1184584
Error codes will not unwind the stack if any of the intermediate functions neglects to do error handling.  Consider:

    // ...
    try {
        Func1();
    }
    catch(...) {
        // Handle error
    }
    // ...

    void Func1() {
        Func2();
    }

    void Func2() {
        Func3();
    }

    void Func3() {
        // ...
       throw 0;
    }
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184585
I think we have a difference in philosophy here.  If you are not using exceptions and a function decides to ignore a returned error code and continue processing, then I would say that is a case where the code has caught and handled all exceptions.  i.e. the code says that the error should't be propagated to the caller, thus the stack should not be unwound in that case.  
0
 

Author Comment

by:cheeseburger
ID: 1184586
Thanks, guys.  I think I was also getting the concepts of trapping errors for program recovery mixed up with trapping errors to catch bugs during development.  
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184587
Yes those are very different.  Programming bugs are best found and reported at the site where they occur.  That is what assert() and its like are for.  Critical Run-time errors are often best handled with exceptions that allow code elsewhere in the program to rectify the situation.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1184588
>> I think we have a difference in philosophy here [...]
I dunno.  Exceptions follow the "philosophy" that errors should only be detected, reported or handled where it makes sense to do so.  Requiring that every function will test and propagate all possible errors is tedious and bug-prone.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184589
Agreed there.  Your point (as I understood it) was that in

int F1()
{
   cout << "error";
   return 1;    
}
int F2()
{
   F1();
   return 0;
}
int F3()
{
   int Err = F2();
  if (Err)
     cout << "F2 failed";
  return Err;
};

The stack is not being unwound, because the error is returned to F2, but not to F3.  My point was that it shouldn't be.  It was unwound enough to report to F2, but F2 decided not to continue the unwinding. essentially F2 caught the exception.  That is F2 catches any error in F1 and reports no errors to F3.  

Thus returning error codes does do stack unwinding (if you let it).  And associated with this--most importantly--is the cleanup of locals.  
0
 
LVL 11

Expert Comment

by:alexo
ID: 1184590
>> Thus returning error codes does do stack unwinding (if you let it).
My point was (I 'll try to be more precise in the future) that exceptions take care of stack unwinding AUTOMATICALLY.  No programmer intervention is required.

Also, not every function can return an error code.  Some functions should return a value.  After all result = sqrt(argument) is much better than rc = sqrt(argument, &result) (or similar using references).
Granted, sqrt() may not be the best example but it illustrates the point.

Exceptions also cleanly(?) separate normal program flow from error handling flow.

OTOH, since the default behavior of an uncaught exception is calling terminate(), exceptions were clearly meant to deal with "exceptional" errors.  Thus they can be used together with traditional error handling methods.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now