Thread: need help?(have done c befor and new to C++)

  1. #1
    Registered User
    Join Date
    Jan 2004

    I need help(have done c befor and new to C++)

    ok i dont know how to do error handling. i was hoping there was a place i can learn that... can anyone point me to the right place?
    Last edited by Panzer_online; 04-24-2004 at 06:57 AM.
    if u c this i will be asking for help

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >ok i dont know how to do error handling.
    Error handling is application specific. As long as you check your return values and initialize your variables properly you'll have done the majority of the work. Past that it's all about how you react to an error.

    Most simple programs will just bail when something unexpected happens, but for larger programs you will need to perform some form of recovery. However, this usually isn't possible at the location that the error occurs, so a good way to move up the call chain to get to a place that is prepared to handle your error would be using exceptions.

    Any good book on C++ will give you more detail than I can here on exceptions, but the idea is like this (off the top of my head):
    #include <cstdlib>
    #include <iostream>
    #include <new>
    using namespace std;
    namespace {
      const int MAX_RECOVERY = 10;
      size_t recovery_index;
      int recovery[MAX_RECOVERY];
    int main()
      for ( int i = 0; i < 20; i++ ) {
        int *p;
        bool recover = false;
        try {
          throw bad_alloc();
          p = new int;
          recover = false;
        catch ( bad_alloc& ) {
          if ( recovery_index == MAX_RECOVERY ) {
            cerr<<"Memory exhausted, no recovery available\n";
            return EXIT_FAILURE;
          else {
            int recovery_left = sizeof *recovery * (MAX_RECOVERY - recovery_index - 1);
            cerr<<"Memory exhausted, recovery available: "<< recovery_left <<" bytes\n";
            p = &recovery[recovery_index++];
          recover = true;
        *p = i;
        cout<< *p <<endl;
        if ( !recover ) {
          delete p;
    My best code is written with the delete key.

  3. #3
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Well I have my handy dandy 900 page book about C++ we are the chapter on exceptions.

    Lemme see if I can nitpick Prelude's code.

    ....posts to follow I'm sure.


  4. #4
    Registered User
    Join Date
    Jan 2004
    hmmm.... ok.. well... i kinder get most of that.. but if i have an int and i put in a char it goes crazy.... how (or point me to the place) would i fix that?
    if u c this i will be asking for help

Popular pages Recent additions subscribe to a feed