10.2(C++)

In this exercise, you need to know how and when to catch an exception.

A class Vector is given, which throws the following exceptions:1. A out_of_range exception, which is thrown whenever a user accesses an element in a vector via an out-of-range index. This exception is thrown by object functions get and set . This exception is defined by C++ in a library file named <stdexcept>

  1. A NonPositiveValueException is thrown whenever a user setting an non-positive element. This exception class is a sub-class of the out_of_range exception class. This exception is thrown in the object function set .

In this exercise, you need to write some catch-blocks following the try-block in the main function. These catch-block should display the information regarding the exceptions caught, as shown in the example input/output.

EXAMPLE INPUT

10
1 2 3 4 5 6 7 8 9 10

3 30
7 70
12 120
5 -10
8 0

EXAMPLE OUTPUT

1 2 3 30 5 6 7 8 9 10 
1 2 3 30 5 6 7 70 9 10 
caught: out_of_range
caught: NonPositiveValueException
caught: NonPositiveValueException

主程序 (不能修改)

#include <stdexcept>
using namespace std;

class NonPositiveValueException : public out_of_range
{
public:
NonPositiveValueException() : out_of_range("non-negative") {
}
};

class Vector
{
private:
int length;
double * elements;

void assign(const Vector & vector) {
length = vector.length;
elements = new double[length];
for (int i = 0; i < length; ++ i) {
elements[i] = vector.elements[i];
}
}

public:
Vector(int size) {
length = size;
elements = new double[size];
}

~Vector() {
delete [] elements;
}

Vector(const Vector & vector) {
assign(vector);
}

Vector & operator = (const Vector & vector) {
delete [] elements;
assign(vector);
return *this;
}

int size() const {
return length;
}

double get(int index) const {
if (index < 0 || index >= length) {
throw out_of_range("index");
}
return elements[index];
}

void set(int index, double value) {
if (index < 0 || index >= length) {
throw out_of_range("index");
}
if (value <= 0) {
throw NonPositiveValueException();
}
elements[index] = value;
}

};

#include <iostream>
using namespace std;

Vector read() {
int size;
cin >> size;
Vector vector(size);
for (int i = 0; i < size; ++ i) {
double value;
cin >> value;
vector.set(i, value);
}
return vector;
}

void print(const Vector & vector) {
for (int i = 0; i < vector.size(); ++ i) {
cout << vector.get(i) << " ";
}
cout << endl;
}

int main() {
Vector vector = read();
for (int i = 0; i < 5; ++ i) {

try {
int index;
double value;
cin >> index >> value;
vector.set(index, value);
print(vector);
}

#include "source.cpp"

}

}

我的答案

catch (NonPositiveValueException & ex) {
    cout << "caught: NonPositiveValueException" << endl;
}
catch (out_of_range & ex) {
    cout << "caught: out_of_range" << endl;
}
上一篇: 11.1 (C++) 下一篇: 10.1 (C++)
支持 makedown语法