Please disable adblock to view this page.

← Go home

Exception Handling (C++)

April 24, 2016
Published By : Pratik Kataria
Categorised in: ,

 

/*
Create a c++ class named Television that has data members to hold the model no.,
screen size and price. Member functions include overloaded insertion and 
extraction operators. If more than 4 digits are entered call the model if screen 
size is smaller than 12 and greater than 70 inches or if price is negative or 
over $5000 then provide the . Write a main function that instantiates a 
television object which allows users to enter data and display data members. 
If an exception is caught then replace all data members with 0.
*/


#include<iostream>

using namespace std;

class Television{

    int modelno;
    double cost;
    double size;
    public:
    
    Television(){
        modelno = 0;
        cost = 0;
        size = 0;
    }

    friend istream& operator >>(istream&input, Television &t){
        int flag = 0;
        cout<<"Enter Model Number:"<<endl;
        input>>t.modelno;
        cout<<"Enter Cost of TV:"<<endl;
        input>>t.cost;
        cout<<"Enter size of TV:"<<endl;
        input>>t.size;
        
        try{
            if(t.modelno > 999) throw(1);
        }
        catch(int i){
            if(i){
                cout<<"Model Number cannot be less than 999"<<endl;
                flag = 1;
            }
        }
        try{
            if(t.size<12 || t.size>70) throw(2);
        }
        catch(int i){
            if(i == 2){
                cout<<"The screen size cannot be smaller than 12 inches or greater than 70 inches."<<endl;
                flag = 1;
            }
        }
    
        try{
            if(t.cost<0 || t.cost>5000) throw(3);
        }
        catch(int i){
            if (i==3){
                cout<<"The cost cannot be negative or greater than $5000"<<endl;
                flag = 1;
            
            }
        }
        if(flag == 1)
        {
            t.modelno = 0;
            t.cost = 0;
            t.size = 0;
        }
        return(input);
    }
    
    friend ostream& operator <<(ostream&output, Television &t){
        output<<"Model Number of TV: "<<t.modelno<<endl;
        output<<"Cost of TV: "<<t.cost<<endl;
        output<<"Size of TV: "<<t.size<<endl;
        return(output);
    
    }

};

int main(){

    Television t;
    
    cin>>t;
    cout<<t;
    
    return 0;

}

View Article Page
Download

App