CS253

CS253: Software Development with C++

Spring 2018

Exception Handling

See this page as a slide show

Exception Handling

CS253 Exception Handling

throw

#include "Loud.h"

Loud a('a');

void foo() {
    Loud b('b');
    throw "oops!";
    Loud e('e');
}

int main() {
    Loud c('c');
    foo();
    Loud d('d');
    return 0;
}
a: Loud::Loud(char)
c: Loud::Loud(char)
b: Loud::Loud(char)
terminate called after throwing an instance of 'char const*'
SIGABRT: Aborted

try #1

#include "Loud.h"

Loud a('a');

void foo() {
    Loud b('b');
    throw "oops!";
    Loud e('e');
}

int main() {
    Loud c('c');
    try {
        foo();
    }
    catch (const char *error) {
        cout << "Caught: " << error << "\n";
    }

    Loud d('d');
    return 0;
}
a: Loud::Loud(char)
c: Loud::Loud(char)
b: Loud::Loud(char)
b: Loud::~Loud()
Caught: oops!
d: Loud::Loud(char)
d: Loud::~Loud()
c: Loud::~Loud()
a: Loud::~Loud()

try #2

#include "Loud.h"

Loud a('a');

void foo() {
    Loud b('b');
    throw "oops!";
    Loud e('e');
}

void bar() {
    Loud f('f');
    foo();
}

int main() {
    Loud g('g');
    try {
        bar();
    }
    catch (const char *error) {
        cout << "Caught an error: “" << error << "”\n";
    }

    Loud d('d');
    return 0;
}
a: Loud::Loud(char)
g: Loud::Loud(char)
f: Loud::Loud(char)
b: Loud::Loud(char)
b: Loud::~Loud()
f: Loud::~Loud()
Caught an error: “oops!”
d: Loud::Loud(char)
d: Loud::~Loud()
g: Loud::~Loud()
a: Loud::~Loud()

catch #1

try {
    throw "oops!";
}

catch (int i) {
    cout << "Caught an int " << i << "\n";
}

catch (const char *error) {
    cout << "Caught an error: " << error << "\n";
}

catch (...) {
    cout << "Caught something\n";
}
Caught an error: oops!

catch #2

// logic_error is-a exception
// runtime_error is-a exception

try {
    overflow_error oops("We overflowed, honest!");
    throw oops;
}
catch (const logic_error &e) {
    cout << "logic_error: " << e.what() << '\n';
}
catch (const runtime_error &e) {
    cout << "runtime_error: " << e.what() << '\n';
}
catch (const exception &e) {
    cout << "exception: " << e.what() << '\n';
}
runtime_error: We overflowed, honest!

rethrow

void foo() {
    throw "*** Hello there";
}

void bar() {
    try {
        foo();
    }
    catch (const char *msg) {
        if (msg[0] == '*')
            cout << "A cheery message: " << msg << '\n';
        else
            throw;      // throw … what?
    }
}

int main() {
    try {
        bar();
    }
    catch (...) {
        cout << "Caught something\n";
    }

    return 0;
}
A cheery message: *** Hello there

Modified: 2018-01-02T11:13

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building