Example:1
Write a C++ program to take input of roll , name and age and display them?
Conditions:
1. Roll no cannot be -ve or zero
2. age cannot be -ve or zero
Sol:
#include <iostream> using namespace std; class invalid_roll { }; class invalid_age { }; void check_roll(int r) { if (r<=0) throw invalid_roll(); } void check_age(int a) { if (a<=0) throw invalid_age(); } int main() { int roll,age; char name[20]; try { cout<<"enter roll number "; cin>>roll; cout<<"Enter name "; cin>>name; cout<<"Enter age "; cin>>age; check_roll(roll); check_age(age); cout<<"roll = "<<roll<<endl; cout<<"name = "<<name<<endl; cout<<"age = "<<age<<endl; } catch(invalid_roll) { cout<<"Error !!!! \nRoll number cannot be -ve or zero"<<endl; } catch(invalid_age) { cout<<"Error !!! \nAge cannot be -ve or zero"<<endl; } return(0); }
Example:2
Write a C++ program to take input of roll , name, and age and display them?
Conditions:
1. Roll no has to be a three-digit number (between 100 and 999)
2. age has to be >=18
Sol:
#include <iostream> using namespace std; class roll_error { }; class age_error { }; void check_roll(int num) { if (num<100 || num>999) throw roll_error(); } void check_age(int num) { if (num<18) throw age_error(); } int main() { int roll,age; char name[20]; try { cout<<" enter roll number "; cin>>roll; cout<<"Enter name "; cin>>name; cout<<"Enter age "; cin>>age; check_roll(roll); check_age(age); cout<<"roll = "<<roll<<endl; cout<<"name = "<<name<<endl; cout<<"age = "<<age<<endl; } catch(roll_error) { cout<<"Error !!!! \nRoll number has to be a 3 digit number"<<endl; } catch(age_error) { cout<<"Error !!! \nAge cannot be <18"<<endl; } return(0); }
Example:3
Write a C++ program to take input of a number check and print whether the number is +ve, -ve or zero?
Sol:
#include <iostream> using namespace std; class positive { }; class negative { }; class zero { }; void check_value(int num) { if (num>0) throw positive(); else if (num<0) throw negative(); else throw zero(); } int main() { int num; cout<<" enter any number "; cin>>num; try { check_value(num); } catch(positive) { cout<<" entered number is positive"<<endl; } catch(negative) { cout<<" entered number is negative"<<endl; } catch(zero) { cout<<" the entered number is zero \n"<<endl; } return 0; }