Catching Derived-Class Exceptions - C++ Class

C++ examples for Class:Exception Class

Introduction

Use inheritance to create various derived classes of runtime_error.

A catch handler specifying the base class can catch derived-class exceptions.

Demo Code

#include <iostream>
#include <stdexcept>

class B {};//from w ww  .j  av  a 2 s  .c o m
class D : public B, public std::runtime_error {
 public:
    D() : std::runtime_error("runtime_error D") {}
};

int main(int argc, const char *argv[]) {
    D derived;

    try {
        throw derived;
    } catch (B b) {
        std::cout << "Caught base class" << std::endl;
    } catch (D d) {
        std::cout << "caught derived class" << std::endl;
        std::cout << d.what() << std::endl;
    }

    return 0;
}

Related Tutorials