Well, I’ve just started to learn Exceptions at college, here is a code that is supposed to throw an exception if an introduced value is out of a range stablished by me…
Thinking and analizing, I think there might me an error with the throws, and some guy tell me in other question that indeed I have not declared any throw…I may have stupid mistakes so sorry for the trouble
Here is my code:
#include <iostream>
#include <exception>
class ExcepcionRango : public std::exception{
protected:
ExcepcionRango::ExcepcionRango(){
}
public:
virtual const char* lanzarExcepcion()=0;
};
class ExcedeRangoInferior : public ExcepcionRango{
public:
ExcedeRangoInferior::ExcedeRangoInferior(){
}
const char* lanzarExcepcion() throw(){ //throw exception
return "Value out of minimal range";
}
};
class ExcedeRangoSuperior : public ExcepcionRango{
public:
ExcedeRangoSuperior::ExcedeRangoSuperior(){
}
const char* lanzarExcepcion() throw(){ //throw exception
return "value out of maximal range";
}
};
int obtainValue(int minimo, int maximo){ //obtain value
int valor; //value
std::cout<<"Introduce a value between "<<minimo<<" and "<<maximo<<" : "<<std::endl;
std::cin>>valor;
return valor;
};
int main(){
ExcedeRangoSuperior* exS = new ExcedeRangoSuperior();
ExcedeRangoInferior* exI= new ExcedeRangoInferior();
int min=3;
int max=10;
int valor=0; //value
try{
valor=obtainValue(min,max);
if(valor<min){
throw exS->lanzarExcepcion();
}
if(valor>max){
throw exI->lanzarExcepcion();
}
}catch(...){
std::cout<<"Exception: ";
}
delete exS;
delete exI;
std::cin.get();
}
PD: the functions lanzarExcepcion() are supposed to throw the message if the inserted value is out of range
Since you are using exceptions in the wrong way, I decided to “refactor” your code to show how it’s most usually done: