Solved

Why use exceptions?

Posted on 1999-01-20
13
155 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
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++.

708 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

15 Experts available now in Live!

Get 1:1 Help Now