好吧,我刚开始在大学学习异常,这是一个代码,如果引入的值超出了我设定的范围,则应该抛出异常......思考和分析,我认为可能会出现错误与投掷,有些人在其他问题中告诉我,确实我没有宣布任何投掷......我可能有愚蠢的错误,很抱歉给你带来麻烦这是我的代码:
#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:如果插入的值超出范围,函数 lanzarExcepcion() 应该抛出消息