Exceptions c ++

0

I have to make some exceptions for possible errors, I would like if in the menu you type a letter you will see a writing error, and in the notes you will not type a note less than 0.0 and neither higher than 5.0. The exceptions must be in a daughter class.

I tried to do it but I really could not.  I did it with header files.

#include<iostream>
#include "classpersona.h"
#include "estudiante.h"
#include "profesor.h"
#include "exception.h"

using namespace std;

void salir();
int opc;
int main(){
    persona p(" "," ");
    estudiante e(" "," "," ",0,0,0,0,0);
    profesor pro(" "," "," "," "," ");
do{  
    system("cls");
    cout<<"Bienvenido"<<endl;
    cout<<"Digite una opcion"<<endl;
    cout<<"1. Datos personales "<<endl;
    cout<<"2.Datos del estudiante "<<endl;
    cout<<"3.Datos del profesor "<<endl;
    cout<<"4.mostrar "<<endl;
    cout<<"5.salir"<<endl;
    cin>>opc;


     switch(opc){
            case 1: p.ingresar();
            break;
            case 2: e.ingresar();
            break;
            case 3: pro.ingresar();
            break;
            case 4: e.mostrar(), p.mostrar(),pro.mostrar();
            break;
            case 5: salir();
            break;
            }  


     }while(opc!=5);

system("pause");
return(0);   
}           



void salir(){
     cout<<"Buen dia"<<endl;
     }

//1 archivo de cabecera.


#include<iostream>
using namespace std;
class persona{
      public:
//atributos
string direccion;
string telefono;

//metodos
virtual void ingresar();
void mostrar();

//constructor      
   persona(string,string);   

};

persona::persona(string _direccion, string _telefono){

          direccion=_direccion;
          telefono=_telefono;
};

void persona::ingresar(){
     cout<<"Ingrese su direccion:  "<<endl;
     cin>>direccion;
     cout<<"Ingrese su Telefono:  "<<endl;
     cin>>telefono;
     system("pause");

     }
void persona::mostrar(){
     cout<<" "<<endl;
     cout<<"La direccion del estudiante es:  "<<direccion<<endl;
     cout<<"El Telefono del estudiante es:   "<<telefono<<endl;

}     


//2 archivo de cabecera.


#include<iostream>
using namespace std;

class estudiante: public persona{
      public:
//atributos
string materia;
float n1;
float n2;
float n3;
float n4;
float promedio;
//metodos
void ingresar();
void mostrar();
void promedio1();
//constructor 
estudiante(string,string,string,float,float,float,float,float);

};    

estudiante::estudiante(string _direccion, string _telefono,string _materia,float _n1,float _n2,float _n3,float _n4,float _promedio): persona(_direccion,_telefono){
                              materia=_materia;
                              n1=_n1;    
                              n2=_n2;  
                              n3=_n3;  
                              n4=_n4;
                              promedio=_promedio;                                  
};       

void estudiante:: ingresar(){
     cout<<"Ingrese la materia:  "<<endl;
     cin>>materia;
    try{
    cout<<"Ingrese la nota 1 "<<endl;
     cin>>n1;
     cout<<"Ingrese la nota 2 "<<endl;
     cin>>n2;
     cout<<"Ingrese la nota 3 "<<endl;
     cin>>n3;
     cout<<"Ingrese la nota 4 "<<endl;
     cin>>n4;
    if(n1||n2||n3||n4>5.0){
          throw n1,n2,n3,n4;
          ;
     }else{
          }
    catch(exception& e){}
         }
}





void estudiante::promedio1(){

promedio=(n1+n2+n3+n4)/4;

}     
void estudiante::mostrar(){
     cout<<" "<<endl;
     estudiante::promedio1();
 cout<<"El promedio del estudiante es: "<<promedio<<endl;    
 cout<<"La materia que cursa es: "<<materia<<endl;

          }

//3 archivo de cabecera.

#include<iostream>
using namespace std;
class profesor:public persona{
  public:
  //Atributos
  string nombre;
  string direccion1;
  string telefono1;
  //Metodos
  void ingresar();
  void mostrar();
  //constructor
   profesor(string,string,string,string,string);    
};

profesor::profesor(string _direccion, string _telefono,string _nombre,string _direccion1,string _telefono1): persona(_direccion,_telefono){

                 nombre=_nombre;
                 direccion1=_direccion1;
                 telefono1=_telefono1;

};
void profesor::ingresar(){
     cout<<"Ingrese el nombre del profesor"<<endl;
     cin>>nombre;
     cout<<"Ingrese la direccion del profesor:  "<<endl;
     cin>>direccion1;
     cout<<"Ingrese el Telefono del profesor:  "<<endl;
     cin>>telefono1;

     }
void profesor::mostrar(){
     cout<<" "<<endl;
     cout<<"El nombre del profesor es:  "<<nombre<<endl;
     cout<<"La direccion del profesor es:  "<<direccion1<<endl;
     cout<<"El Telefono del profesor es:   "<<telefono1<<endl;
     system("pause");
}     

// archivo de cabecera de la exepcion

#include<iostream>
using namespace std;
class exception: public persona{
      public:
             catch(exception* e){
    cout<<"Error"<<endl;
 }             

};
    
asked by Nicolas RUIZ VILLAQUIRAN 27.05.2018 в 02:11
source

2 answers

2
  

I have to make some exceptions for possible errors, I would like if in the menu you type a letter you will see a writing error, and in the notes you will not type a note less than 0.0 and neither higher than 5.0. Exceptions must be in a daughter class.

None of this makes sense in C ++.

The exceptions are, for exceptional cases.

As the name implies, exceptions should be used when something exceptional happens during code execution. They are an error control mechanism, not a mechanism to control the flow of the program.

That the user enter an unexpected data, or data in an inappropriate range is not something exceptional (users are idiots 1 ) if not something that is part of the normal flow of the program.

Something terrible happened! I'll try to fix it ... or delegate.

The usual and recommended regarding the use of exceptions is to detect the error at run time and do everything possible to restore the normal operation of the application; if the latter is not possible: the exception must be moved through the call stack until someone can take over or end the application if in no context is known to solve the problem.

For this reason, it does not make sense that the exceptions belong to a restrictive class hierarchy, unless they are later re-released as a more generic exception.

Proposal.

To check if in the menu you type a letter you should not capture the user input in an integer, capture a string that you will later transform to a number:

std::string opc;
std::cin >> opc;

try
{
    switch (std::stoi(opc))
    {
        // Hacer cosas...
    }
}
catch (const std::invalid_argument &no_es_numero)
{
    std::cout << "Error de escritura: '" << opc << "' no es una opcion valida\n";
}

The std::stoi function transforms a string into a number, if it can not doing no conversion throws an exception of type std::invalid_argument that you can capture and act on accordingly.

Regarding the notes:

void estudiante:: ingresar(){
    std::cout << "Ingrese la materia:  \n";
    std::cin >> materia;
    try{
        float notas[4]{};

        for (int nota = 0; nota != 4; ++nota) {
            std::cout << "Ingrese la nota " << (nota + 1) << '\n';
            std::cin >> notas[nota];
            if (notas[nota] < .0f || notas[nota] > 5.f) {
                throw std::out_of_range{std::to_string(notas[nota]}
            }
        }

        n1 = notas[0];
        n2 = notas[1];
        n3 = notas[2];
        n4 = notas[3];
    }
    catch (const std::out_of_range &nota_no_valida) {
        std::cout << "Una nota esta fuera de rango: " << nota_no_valida.what();
    }
}

You have a lot of bad things in your code. The catch should be paired with a try , they should not be inside of them. Regarding your throw , you can not throw several objects at the same time, the instruction throw n1,n2,n3,n4 will throw the last value ignoring the rest; but it makes little sense to throw a number as an exception, so I replaced it with the exception std::out_of_range , which makes sense in this context.

If you notice, in case of exception the values n1 , n2 , n3 and n4 are not modified, this is a good practice associated with the use of exceptions: if an error occurs during execution of the code of the class estudiante it is advised that the instance remains in a usable state (that it recovers adequately from the error).

  • Programming is a race between software engineers striving to create the best and greatest idiot-proof programs, and the Universe trying to produce better and bigger idiots. For now, the universe is winning - Rick Cook -
  • answered by 28.05.2018 / 09:02
    source
    0

    An example of exception handling in C ++ can help you:

    #include "iostream"
    #include <exception>
    #include <cstdlib>
    
    
    using namespace std;
    
    
    
    enum error {datos_no_validos};
    
    
    void validar(double radio, double diametro) throw(error){
      if(radio <= 0.0 && diametro <= 0.0){
        throw datos_no_validos;
      }
    }
    
    class Circulo{
    private:
        double radio;
        double diametro;
    public:
        static const double PI=3.1459;
        Circulo(){cout<<"objeto circulo creado"<<endl;}
        virtual ~Circulo(){cout<<"objeto circulo destruido"<<endl;}
        void setRadio(double r){this->radio=r;}
        double getRadio(){return this->radio;}
        void setDiametro(double d){this->diametro=d;}
        double getDiametro(){return this->diametro;}
        double calc_diametro(){return this->diametro*PI;}
        double calc_area(){return PI*(this->radio*this->radio);}
    };
    
    
    int main(){
        Circulo circulo=Circulo();
        double radio,diametro;
        cout<<"Introduce radio: "<<endl;
        cin>>radio;
        cout<<"Introduce diametro: "<<endl;
        cin>>diametro;
        try{
          validar(radio,diametro);
        }catch(error e){
            switch(e){
              case datos_no_validos: cout<<"Datos invalidos!!!"<<endl;break;
              default: cout<<"No especificada"<<endl;break;
            }
        }
    
    
        circulo.setRadio(radio);
        circulo.setDiametro(diametro);
    
        cout<<"diametro: "<<circulo.calc_diametro()<<" , area: "<<circulo.calc_area()<<endl;
        return 0;
    }
    

    I hope it helps you. Thanks for correcting my response.

        
    answered by 27.05.2018 в 21:27