Exception Handling-01
Exception Handling-01
#include<iomanip>
using namespace std;
int main()
{
float x,y;
while(1)
{
try
{
}
catch(const char *x)
{
cout<<x;
}
}
return 0;
}
int main()
{
try
{
int n,m,i;
cout<<" Enter the array length : ";
cin>>n;
int a[n];
cout<<" ENTER ARRAY ELEMENTS -\n";
for(i=0;i<n;i++){
cout<<setw(20)<<" Element at index "<<setw(2)<<i<<": ";
cin>>a[i];
}
cout<<" ARRAY ELEMENTS ARE : ";
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<"\n Enter which number of index you want to access : ";
cin>>m;
if(0>m || m>=n){
throw " INVALID INDEX!\n\n";
}
cout<<" You've accessed index "<<m<<" successfully! \n\n";
}
catch(const char *x){
cout<<x;
}
return 0;
}
}
catch(int x)
{
cout<<"You have thrown an integer. It is "<<x<<endl;
}
catch(string x)
{
cout<<x<<endl;
}
return 0;
}
throw 1;
throw string("You've thrown a string");
}
catch(int x)
{
cout<<"You have thrown an integer. It is "<<x<<endl;
}
catch(string x)
{
cout<<x<<endl;
}
return 0;
}
CODE-05: #include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float x,y;
while(1)
{
try
{
cout<<setw(26)<<"Enter the divisor : ";
cin>>x;
cout<<setw(26)<<"Enter the denominator : ";
cin>>y;
if(y<0 || x<0)
{
throw string(" Negative numbers are not allowed.\n O P E R A
T I O N F A I L E D!\n\n");
}
if(y==0)
{
throw string(" Denominator can't be zero.\n O P E R A T I O N
F A I L E D!\n\n");
}
cout<<" "<<x<<"/"<<y<<" = "<<x/y<<" \n O P E R A T I O N S U C C
E S S F U L!\n\n";
}
catch(string x)
{
cout<<x;
}
}
return 0;
}
CODE-06: #include<iostream>
#include<iomanip>
using namespace std;
int main()
{
while(1)
{
try
{
int n,m;
cout<<"Enter the length of array : ";
cin>>n;
int a[n];
for(int i=0; i<n; i++)
{
cout<<"Element at index "<<setw(2)<<i<<setw(2)<<" : ";
cin>>a[i];
if(a[i]<0)
{
throw string("Negative is not allowed!\nOPERTION FAILED!\n\n");
}
}
cout<<"Enter the index you want to access : ";
cin>>m;
if(m<0 || m>=n)
{
throw string("Array index is not valid!\nOPERATION FAILED!\n\n");
}
cout<<"Element at index "<<m<<" : "<<a[m]<<"\nOPERATION SUCCESSFUL!\n\
n";
}
catch(string s)
{
cout<<s;
}
}
return 0;
}
CODE-07: #include<iostream>
#include<iomanip>
#include<string>
int main()
{
while(1)
{
try
{
int age;
cout<<"Enter age : ";
cin>>age;
if(age<=0)
{
throw string(to_string(age)+" is an invalid age!\n\n");
}
if(age>120)
{
throw string(to_string(age)+" is an invalid age!\n\n");
}
cout<<"Age : "<<age<<"\n\n";
}
catch(string s)
{
cout<<s;
}
}
return 0;