Skip to main content

Exception with argument and specification program

Short answer

Define a RangeError class with msg and value. Function checkAge throws RangeError for negative age or int for age>120, with specification throw(RangeError,int). Main catches RangeError to print msg/value, catches int to print age too large.

Write a meaningful program illustrating the use of both Exception with argument and Exception Specification for function.

Exception with argument – the thrown object carries data (here, a class object with a message and a value), which the handler receives as its argument. Exception specification – a function declares which exception types it may throw: void f() throw(int, MyError);. (An empty list throw() means it throws nothing. This feature is used in older textbooks and is deprecated in modern C++, but it is still the expected syntax in this syllabus.)

#include <iostream>
using namespace std;

class RangeError {                      // exception with argument
public:
    const char *msg;
    int value;
    RangeError(const char *m, int v) : msg(m), value(v) {}
};

// exception specification: this function can throw only RangeError or int
void checkAge(int age) throw(RangeError, int) {
    if (age < 0)
        throw RangeError("Age is negative", age);
    if (age > 120)
        throw age;                      // plain int exception
    cout << "Valid age: " << age << endl;
}

int main() {
    int ages[] = {25, -5, 150};
    for (int i = 0; i < 3; i++) {
        try {
            checkAge(ages[i]);
        }
        catch (RangeError e) {          // receives object with data
            cout << e.msg << " (" << e.value << ")" << endl;
        }
        catch (int n) {
            cout << "Age too large: " << n << endl;
        }
    }
    return 0;
}

Output

Valid age: 25
Age is negative (-5)
Age too large: 150

If checkAge threw a type not listed in its specification, unexpected() would be called and the program would terminate. Compile with -std=c++98 (or c++03) because dynamic exception specifications were removed in C++17.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 10 questions →