I'm learning c ++ and I wanted to try a code using try and catch. So I wrote a program that would deliberately send an error out_of_range:
#include <iostream>
#include <stdexcept>
class foo{
public:
foo(int s) :elem{new double[s]} {}//constructor de foo
double& operator[](int i);
private:
double* elem;
};
double& foo::operator[](int i)
{
try{
std::cout << "se accedio a elem[" << i << "] satisfactoriamente\n";
return elem[i];
}
catch(std::out_of_range){
std::cout << "Ups " << i << " esta fuera del rango de elem\n";
throw std::out_of_range{"Vector::operator[]"};
}
}
void error() //Esta función esta creada para deliberadamente lanzar el error out_of_range
{
foo boo(1);
boo[1] = 1;
boo[2] = 2;
}
int main()
{
error();
}
The problem is that even when you try to write a value in boo [1] and boo [2] the output prints
se accedio a elem[1] satisfactoriamente
and continue without throwing any errors.
(It seems that when I try to throw errors deliberately I do not get any: P)