Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 212
  • Last Modified:

Why use exceptions?

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
cheeseburger
Asked:
cheeseburger
  • 6
  • 4
  • 2
  • +1
1 Solution
 
cheeseburgerAuthor Commented:
Adjusted points to 200
0
 
pellepCommented:
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
 
nietodCommented:
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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
nietodCommented:
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
 
alexoCommented:
Exceptions also take care of unwinding the stack (and destroying local objects) for you.
0
 
nietodCommented:
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
 
alexoCommented:
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
 
nietodCommented:
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
 
cheeseburgerAuthor Commented:
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
 
nietodCommented:
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
 
alexoCommented:
>> 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
 
nietodCommented:
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
 
alexoCommented:
>> 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now