Solved

Why use exceptions?

Posted on 1999-01-20
13
182 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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

 
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
 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

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.

Question has a verified solution.

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

Suggested Solutions

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

808 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