class node {
public:
enum status {
ok,
error
};
status error_code;
node() {
if (no error)
error_code = ok;
else
error_code = error;
}
};
error_code.
error_code wouldn't exist.
error_code was static, the constructor could completely bomb out.
#include <node.h>
int main() {
// No error checking.
node n1;
// Do some error checking.
node n2;
if (n2.error_code != node::ok) {
// handle error.
}
}
n1 and n2 must be constructed, always.
class node {
public:
enum status {
ok,
error
};
node(status & s = st) {
if (no error)
s = ok;
else
s = error;
}
private:
static status st;
};
static is necessary; the compiler needs to know the default value.
#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.
}
}
#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");
}
};
exception::what() requires them.
#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);
}
}
n is unambiguously good or bad.
n has to be in the try block.
class node {
public:
node(void (* efun)(const char *) = df) {
if (some terrible error)
efun("some terrible error");
}
private:
static void df(const char *);
};
#include "node.h"
#include <iostream>
#include <cstdlib>
static void efun(const char * emsg) {
cerr << "Error during node create: "
<< emsg << ".\n";
exit(EXIT_FAILURE);
}
int main() {
node n1;
node n2(efun);
}
This page last modified on 18 February 2003.