Lecture Notes for Advanced Programming II

2 October 2001 - Exception Examples


Error Handling With Parameters

class node {

  public:

    enum status {
      ok,
      error
      };

    node(status & s = st) { 

      // Assume no error.

         s = ok;

      // Here's an error.
	 
	 s = error;
      }

  private:

    static status st;

  };


Handling Parameter Errors

#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

#include <exception>

class node {

  public:

    struct node_exception : public exception {
      const char * emsg;
      node_exception(const char * s) : emsg(s) { }
      const char * what(void) const { return emsg; }
      };


    node() { 

      // Here's an error.
	 
         throw node_exception("some terrible error");
      }

  };


Handling Exception Errors

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

int main() {

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

  }


Which is Better?


This page last modified on 2 October 2001.