class array exception

Hey!

my english is not the best, sorry for mistakes.

I'm new to c++ and programming with classes.
I have created a class template "CArray" to work with dynamic arrays.
In addition to that, Ive created an exception class "XOutOfBounds".
So whenever the user is asking for an index which is not in the array's index the exception "XOutOfBounds" is thrown.In theory, but it doesnt work with my code.

So for example if the user is asking for array[6], but the array has only 3 array fields, the exception has to be thrown.

Right now I have added throw XOutOfBounds in my operator function, which returns the index of an array field,it makes no sense there I guess. Where should I throw the exception instead?


Headerfile CArray:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#pragma once
#include <cstring>
#include "XOutOfBounds.hpp"

template <typename T, unsigned int N>

class CArray{

public:

	CArray(){									
		size = N;
		entries = new T[size];


	}
	~CArray(){
		delete[]entries;
		entries = nullptr;
	}

	CArray(const CArray & other){

		//Tiefe Kopie
		size = N;
		entries = new T[size];
		memcpy(entries,other.entries,sizeof(T)*size);

	}

	T& operator[](unsigned int index){									//return arrays index
		if (index>size){
			throw XOutOfBounds("Index wurde überschritten!");}

		return entries[index];

	}


private:

	T* entries;
	unsigned int size;

};



CPP of XOutOfBounds


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "XOutOfBounds.hpp"
#include <string>


XOutOfBounds::XOutOfBounds(const char* msg){
	m_msg = msg;
}

XOutOfBounds::~XOutOfBounds() throw(){

}

const char* XOutOfBounds::what(){
	return  m_msg.c_str();
}


Last edited on
Your operator is actually the best place to check the index and through an exception.
If it doesn't work the problem must be somewhere else.
hmm okay, do you have a hint ?
The code itself is correct and is not sending error messages so Im not sure where to start
It would help if you posted a small self contained complete program that illustrates your problem.


Since an index of size is also out-of-bounds, it should be
 
if (index >= size)

Topic archived. No new replies allowed.