CS253: Software Development with C++

Spring 2018

Old-fashioned Error Handling

See this page as a slide show

CS253 Old-fashioned Error Handling

The Old Days

Out-of-band value

#include "Loud.h"
#include <unistd.h>

Loud a='a';

int foo() {
    Loud b('b');
    if (getuid() != 0) // root?
        return -1;
    return 42;
}

int main() {
    Loud c('c');
    if (foo() < 0)
        return 1;
    Loud d('d');
    return 0;
}
Loud::Loud('a')
Loud::Loud('c')
Loud::Loud('b')
Loud::~Loud()
Loud::~Loud()
Loud::~Loud()

That works, but …

exit

#include "Loud.h"
#include <unistd.h>

Loud a='a';

void foo() {
    Loud b('b');
    // MUST be super-user!
    if (getuid() != 0)
        exit(1);
}

int main() {
    Loud c('c');
    foo();
    Loud d('d');
    return 0;
}
Loud::Loud('a')
Loud::Loud('c')
Loud::Loud('b')
Loud::~Loud()

abort

#include "Loud.h"
#include <unistd.h>

Loud a='a';

void foo() {
    Loud b('b');
    if (getuid() != 0)
        abort();
}

int main() {
    Loud c='c';
    foo();
    Loud d='d';
    return 0;
}
Loud::Loud('a')
Loud::Loud('c')
Loud::Loud('b')
SIGABRT: Aborted

assert

#include "Loud.h"
#include <cassert>
#include <unistd.h>

Loud a('a');

void foo() {
    Loud b('b');
    assert(!getuid());
}

int main() {
    Loud c('c');
    foo();
    Loud d('d');
    return 0;
}
a.out: c.cc:9: void foo(): Assertion `!getuid()' failed.
Loud::Loud('a')
Loud::Loud('c')
Loud::Loud('b')
SIGABRT: Aborted

Division by Zero

#include "Loud.h"
#include <unistd.h>

Loud a('a');

static int n = 0;

void foo() {
    Loud b('b');
    if (getuid() != 0)
        n = 1/n;
}

int main() {
    Loud c('c');
    foo();
    Loud d('d');
    return 0;
}
SIGFPE: Floating point exception

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:55

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building