I have a question about exceptions.

This is a discussion on I have a question about exceptions. within the C++ Programming forums, part of the General Programming Boards category; I don't really understand the underlying purpose of throwing an exception. I know that the programmer can allow for correction ...

  1. #1
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901

    I have a question about exceptions.

    I don't really understand the underlying purpose of throwing an exception. I know that the programmer can allow for correction of the error without throwing the exception, and they could cause the program to abort without an exception as well, so why exactly throw an exception. Instead of using the try and catch, why not just try and write code that corrects the error or allows the user to correct the error. I know it's necessary and has a useful purpose, but so far I just can't grasp what that is. Any examples of exceptions that are necessary?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >why not just try and write code that corrects the error or allows the user to correct the error.
    How? Exceptions are a means of reporting that an error occurred. Writing code that corrects the error implies that you've somehow discovered that there was an error. So if you don't use exceptions, you have to use a functional equivalent, like returning error codes.

    >I know it's necessary and has a useful purpose, but so far I just can't grasp what that is.
    They're not necessary, but they are an improvement when used correctly. Code written for exceptions doesn't have error handling code intermixed with the meaty goodness (note that error handling usually takes about 1/3 of the code base in an average application). This makes code clearer and shorter. Also, rather than failing quietly for months before exploding in a glorious meltdown, unhandled exceptions will fail predictably, safely, and immediately.

    >Any examples of exceptions that are necessary?
    There are none. Exceptions can be replaced with a number of error reporting techniques to the same effect.
    My best code is written with the delete key.

  3. #3
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,467
    Stroustrup explains the exception handling mechanism in his book in a very clear way.

    What I guess you need to do, besides buying the book , is to remember that C++ allows for modularization of your code. A class may know about an error, but not know what to do with it, while the user of that class may know what to do, but not how to detect the error. And speaking of classes, we can say a namespace or an entire library.

    The key concepts are thus error reporting (which is usually done by the module being called) and error handling (which is usually done by the caller). C++ Exceptions make that separation allowing a bridge between the two by means of error objects.

    For this to make more sense you have to add another agent to your programming experience. You are probably used to looking at your projects as I, the programmer, and Them the users of my program. And yet there is in fact a third Agent. For many things from exception handling to OOP design you should think in terms of class designer, class user and program user. For a lone programmer, the first two may be embodied in one person (the programmer). But you still need to look at things that way, not forgetting that you have two roles and understanding when you are coding for which role.

    Take a look at a recent thread on this forums asking about a strange output regarding allocation of memory. The <new> header defines a the new operator and what happens when you try to allocate memory that you don't have.

    The Class Designer or the (library designer if you want) knows how to detect when this happens. But what does he know what to do about it? Should he immediatly abort? Should he move on? He doesn't know. He delegates that decision to whoever calls the code. So... he throws an exception. If unhandled that exception will force the code to abort.

    Meanwhile, you the User of the Class where trying to allocate some very big arrays. And decided that if the computer where the program is running didn't have enough memory, you should inform the program user and ask him for a smaller number. But how do you know if there is enough memory? You can't obviously wait for the program to crash. It will be too late then. What you do is that you try to allocate and catch std::bad_alloc if it happens. Inside the catch block you do what you set yourself to do; inform the user and request for new input (it's obvious to you the class user, that the designer couldn't ever possibly have guessed this).

    That's exception handling in the words of a newbie. Certainly others can correct or add to what I said.
    Last edited by Mario F.; 11-09-2006 at 11:48 AM.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  4. #4
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    I wouldn't say exceptions are necessary. It's one way of dealing with unusual, unexpected, problems.

    For everyday problems like "file not found", you don't usually use an exception.

    I think the idea is to move the exception handling "off to the side", instead of cluttering-up the main body of your code.

    Thinking In C++ Volume II (FREE online) has an entire chapter on exceptions. I Haven't read it for awhile, so I don't remember exactly what it says. But, there is a section on when to use exceptions, and when not to use exceptions.

  5. #5
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,467
    Quote Originally Posted by DougDbug
    I wouldn't say exceptions are necessary. It's one way of dealing with unusual, unexpected, problems.

    For everyday problems like "file not found", you don't usually use an exception.

    I think the idea is to move the exception handling "off to the side", instead of cluttering-up the main body of your code.
    It's something I'm not sure I agree entirely. Don't take me wrong please. I'm aware it may be the result of my ignorance. But I would certainly like to hear more on this.

    You see, exceptions seem to me more a tool for programmers aimed at programmers. If we consider a project in isolation, I would think that yes, it's quiet prossible to delineate our own error handling strategy that is not necessarily implemented in terms of C++ exceptions.

    But what about code reuse? Are we sure that our strategy will serve us well in the future if we want to import modules to another project? It's probably very difficult to implement a separation from error reporting and error handling. And perhaps it makes little sense considering C++ provides us with that tool already; Exceptions.

    And what about the ever growing world of redistributable software and community development? Doesn't it make sense to make exceptions an important part of the error handling techniques, instead of forcing everyone to adapt to what can possibly be an alien approach, or worst, let anyone choose their own methods?

    Exception handling is error handling. Certainly we should not become blind to other possibilities. But whenever I want to report an error at a low level in my design, and I don't know how to handle it, exceptions are the way delegate that decision to those parts of my code at an higher level that are more informed as to take a decision. Why avoid that?
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Why avoid that?
    Indeed. But it seems to me that you're confusing exceptions with the more abstract concept of delayed error handling (ie. separation of reporting and recovery). You can implement delayed error handling with any strategy; exceptions just make it cleaner. Your conclusions are okay, but how you reach them is a little screwy in my opinion.
    My best code is written with the delete key.

  7. #7
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,467
    Ok. It had to be something like that; I missread Doug's post.
    ... and I need a lot more reading on this subject.

    It's funny actually. I handled pointer syntax, const correctness, alien new concepts like smart pointers, functors and binders, templates, and many other things that when I took a first look at them I thought I was going to eventually give up.

    But of all the things, definitely, I never thought error handling would be the thing that I'm taking more time doing the brain switch.

    "Why on earth he spends 34 pages discussing this!?" <--- these were more or less my famous last words when I first started taking a serious look at it a couple of months ago.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  8. #8
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Quote Originally Posted by DougDbug
    I wouldn't say exceptions are necessary. It's one way of dealing with unusual, unexpected, problems.

    For everyday problems like "file not found", you don't usually use an exception.
    You could make a case that it is better to have a single, uniform error handling scheme versus mixing exceptions with other error handling schemes such as error codes.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,299
    Quote Originally Posted by Cat
    You could make a case that it is better to have a single, uniform error handling scheme versus mixing exceptions with other error handling schemes such as error codes.
    It is also possible to make a case that it is better for an error handling strategy to employ a range of error reporting methods (exceptions, error codes, assertions) corresponding to severity of the errors to be handled and feasibility of recovering from them.

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Often it is said that things like "file not found" should not throw exception, because such errors are to be expected.

    The question, though, is, "Who expects them?" A function that receives a file name as a parameter and then is supposed to do something with that file does not expect this file not to exist. The place that expects the file not to exist (or to be in an invalid format) is the place that asks the user for the file name.

    As such, there are two choices. Either the place that asks can validate existence and well-formedness of the file. Especially in the case of testing a complicated format, this can lead to enormous code duplication and runtime overhead (the file has to be parsed twice).
    Or the place that asks calls into the place that parses and simply catches any exception coming out of it, since that is expected.

    So whenever someone tells you, "Don't throw an exception for this, it's expected," keep in mind that expectations are a matter of perspective.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,467
    Adding to that, I personally think that some circles use the interpretation of the word "exception" as a case to decide wether or not to use throw. I don't think that was the intention of the language implementator.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  12. #12
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Quote Originally Posted by Mario F.
    Adding to that, I personally think that some circles use the interpretation of the word "exception" as a case to decide wether or not to use throw. I don't think that was the intention of the language implementator.
    Yeah, I use the keyword "class" despite being boorish and uneducated
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,299
    Well, yes, the notion of expected depends on your expectations.

    There is sometimes a case for throwing an exception when a file is not found, for example if the program is unable to function correctly if the file is not successfully read. That is an issue of the programmer expecting the file WILL exist, and the program design relying on that expectation being met.

    The more usual argument I've seen for not throwing exceptions with file handling is that various errors (eg not finding a file, encountering end of file, etc) do not have significant consequences. For example, a program that processes a set of files simply goes on to the next file if it can't find one or a program that is processing all the contents of a file would routinely check for end of file indication anyway. In the first case (file does not exist) there is no need to throw exceptions, as the batch processing logic would recover from the error anyway. In the second case (end of file encountered) there is no need to throw exceptions as the end of file condition is a rather obvious point where processing would end, and no further recovery (other than closing the file, which would nominally happen no matter how the processing completes) is needed. I suppose we could argue that this is a matter of expectations (eg it is reasonable to expect that a programmer would do things in this way unless they have a specific reason not to), and then we come into arguments of "common practice". If 95% (to pluck a figure from the air) of all file processing codes can be expected to routinely recover if they don't find a file or if they encounter an end of file, does it make sense to report an error in a manner that is better suited for the other 5% of cases?

  14. #14
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,467
    Gosh I'm so confused...

    EDIT: But isn't true that the reason to decide or not to throw should be based solely on who/what is going to handle the error?

    - The code that causes the error can handle it. Strong case against exceptions.
    - The code can't handle it. Strong case for exceptions.

    I'm sorry to keep hitting on the same thing. I'm daft. It's just that my perfect world is crashing with every post you gurus make.
    Last edited by Mario F.; 11-09-2006 at 05:57 PM.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  15. #15
    Registered User
    Join Date
    Jan 2005
    Posts
    7,318
    The answer is still the same as before. In general, use exceptions in exceptional situations. It is just important to remember that many factors are involved in what determines whether a situation is exceptional or not.

    The file not found example is used assuming the reader understands that the situation is something like a situation where code attempts to open a file with an unchecked, user specified filename for a non-essential file. Of course you can have a file not found error that is exceptional and warrants an exception (Mario F., I think you did recently), but that is not what the assumed situation is referring to.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Exceptions
    By sean in forum C# Programming
    Replies: 4
    Last Post: 10-01-2004, 12:48 AM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. Throwing exceptions with constructors
    By nickname_changed in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2003, 09:21 AM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 12:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21