Lecture Notes for Advanced Programming II

1 October 2002 - Exception Examples


Error Handling With Instance Variables

class node {

  public:

    enum status {
      ok,
      error
      };

    status error_code;

    node() { 

      if (no error)
        error_code = ok;
      else
	error_code = error;
      }

  };


Using Error Instance Variables

#include <node.h>

int main() {

  // No error checking.

     node n1;
  
  // Do some error checking.

     node n2;
     if (n2.error_code != node::ok) {
       // handle error.
       }
  }


Error Handling With Parameters


Using Error Parameters

#include <node.h>

int main() {

  // No error checking.

     node n1;
  
  // Do some error checking.

     node::status s;
     node n2(s);
     if (s != node::ok) {
       // handle error.
       }
  }


Error Handling With Exceptions


Using Exception Errors

#include "node.h"
#include <iostream>
#include <cstdlib>

int main() {

  try {
    node n;
    }
  catch (node::node_exception ne) {
    std::cerr << "Error during node create:  "
              << ne.what() << ".\n";
    exit(EXIT_FAILURE);
    }

  }


Error Handling With Functions


Using Error Functions

#include "node.h"
#include <iostream>
#include <cstdlib>

static void efun(const char * emsg) {
  std::cerr << "Error during node create:  "
            << emsg << ".\n";
  exit(EXIT_FAILURE);
  }

int main() {

  node n1;
  node n2(efun);

  }


Which is Better?


This page last modified on 1 October 2002.